建造者模式 和 外观模式

这两种模式很像, 都是将一个复杂的流程统一用一个方法进行包装, 方便外界使用.

建造者模式更像是 外观模式的一种特里, 只对一个类的复杂初始化流程进行包装

建造者模式

简介: 就是一个类的构造方法可能很复杂, 由于系统的限制等原因, 可能很多初始化逻辑不能放在构造函数里, 所以就需要一个类来统一这种构建流程, 让外界不需要知道具体的复杂构造逻辑, 就能获取目标类的实例.
代码

cpp 复制代码
class Building
{
private:
	string foundation;
	string main_wall;
	string floor;
public:
	
	Building() {};
	void build_foundation() 
	{ 
		cout << "must be first step" << endl;
		foundation = "create_foundation"; 
	}
	void build_main_wall() 
	{ 
		cout << "must be second step" << endl;
		main_wall = "build main wall"; 
	}
	void build_floor() 
	{ 
		cout << "must be third step" << endl;
		floor = "build floor"; 
	}

	// 声明为友元函数, 可以访问私有变量
	friend ostream& operator << (ostream& os, const Building* b);
};



ostream& operator << (ostream& os, const Building* b)
{
	os << b->foundation << "," << b->main_wall << "," << b->floor << endl;
	return os;
}


class Builder
{
public:
	Builder() {};
	Building* build_building()
	{
		Building* b = new Building();
		b->build_foundation();
		b->build_main_wall();
		b->build_floor();
		return b;
	}
};


int main()
{
	Builder* builder = new Builder();

	Building* building= builder->build_building();

	cout << building << endl;
	return 0;
}

执行结果

外观模式

简介: 外观模式: 一般情况下, 都是因为老系统比较负责, 用一个类统一包装一下业务逻辑, 方便新系统使用

比如打车到某个地方, 分为三个部分, 然后用一个方法统一执行这些步骤, 统一打车的业务逻辑

1: 网络约车

2: 验证手机尾号

3: 驾驶员驾驶汽车到达目的地

4: 付款

代码

cpp 复制代码
class SystemCallCar
{
public:
	void run() { cout << "call car" << endl; }
};


class SystemVertifyPhone
{
public:
	void run() { cout << "vertify phone" << endl; }
};


class ReachTargetPlace
{
public:
	void run() { cout << "drive car reach target place"; }
};


class Pay
{
public:
	void run() { cout << "pay money" << endl; }
};



class Face
{
public:
	void run()
	{
		SystemCallCar* s1 = new SystemCallCar();
		SystemVertifyPhone* s2 = new SystemVertifyPhone();
		ReachTargetPlace* s3 = new ReachTargetPlace();
		Pay* s4 = new Pay();
		s1->run();
		s2->run();
		s3->run();
		s4->run();
	}
};


int main()
{
	Face f;
	f.run();
	return 0;
}

执行结果

相关推荐
青草地溪水旁5 分钟前
设计模式(C++)详解—原型模式(2)
c++·设计模式·原型模式
青草地溪水旁11 分钟前
设计模式(C++)详解—原型模式(3)
c++·设计模式·原型模式
C++_girl23 分钟前
缓存未命中
c++·缓存
bikong736 分钟前
桥接模式,打造灵活可扩展的日志系统C++
c++·桥接模式
艾莉丝努力练剑40 分钟前
【C++】类和对象(下):初始化列表、类型转换、Static、友元、内部类、匿名对象/有名对象、优化
linux·运维·c++·经验分享
疋瓞1 小时前
C++_STL和数据结构《1》_STL、STL_迭代器、c++中的模版、STL_vecto、列表初始化、三个算法、链表
数据结构·c++·算法
三体世界1 小时前
测试用例全解析:从入门到精通(1)
linux·c语言·c++·python·功能测试·测试用例·测试覆盖率
Bear on Toilet1 小时前
继承类模板:函数未在模板定义上下文中声明,只能通过实例化上下文中参数相关的查找找到
开发语言·javascript·c++·算法·继承
努力努力再努力wz2 小时前
【c++进阶系列】:map和set的模拟实现(附模拟实现的源码)
java·linux·运维·开发语言·c++
lingran__5 小时前
速通ACM省铜第三天 赋源码(Double Perspective和Trip Shopping和Hamiiid, Haaamid... Hamid?)
c++·算法