6.建造者模式

建造者模式的优缺点

优点:
  1、降低代码耦合度。在建造者模式中,客户端不需要知道产品内部是如何实现的,我们只需得到产品的对象。并且使用导演者和建造者分离组装过程和组件具体构造过程,具有灵活的扩展性。

  2、优秀的扩展性。具体建造者相互独立,方便扩展,符合开闭原则。

缺点:
  一定的使用范围限制。建造者模式的产品的组件基本相同,如果产品的差异性较大,建造者模式就不适用了。


比较
  跟工厂方法模式对比:建造者模式和工厂模式同样是创建一个产品,工厂模式就是一个方法,而建造者模式有多个方法,并且建造者模式是有顺序的执行方法。就是说建造者模式强调的是顺序,而工厂模式没有顺序一说。

  建造者模式和模板方法模式非常的相似,只是比模板方法模式多了一个类,指挥类, 该类就是模板中基类的固定算法的功能相同,它是一个创建对象的固定算法。 他两的使用范围区分就看构建的算法是否需要另外创建一个类。

                            

#include <iostream>
using namespace std;

// Builder(建造工厂)
class Builder
{
public:
	virtual void build_head() = 0;            // head
	virtual void build_body() = 0;            // body
	virtual void build_arms() = 0;            // arm
	virtual void build_legs() = 0;            // leg
	virtual void build_private_part() = 0;    // private part
};

// man
class ManBuilder : public Builder
{
public:
	void build_head()
	{
		cout << "build man head" << endl;
	}

	void build_body()
	{
		cout << "build man body" << endl;
	}

	void build_arms()
	{
		cout << "build man arm" << endl;
	}

	void build_legs()
	{
		cout << "build man leg" << endl;
	}

	void build_private_part()
	{
		cout << "build xiao dd" << endl;
	}
};

// woman
class WomanBuilder : public Builder
{
public:
	void build_head()
	{
		cout << "build woman head" << endl;
	}

	void build_body()
	{
		cout << "build woman body" << endl;
	}

	void build_arms()
	{
		cout << "build woman arm" << endl;
	}

	void build_legs()
	{
		cout << "build woman leg" << endl;
	}

	void build_private_part()
	{
		cout << "build xiao mm" << endl;
	}
};


// NuWa(指挥官)
class NuWa
{
public:
	NuWa(Builder* b)
	{
		builder = b;
	}

	void Create()
	{
		cout << "开始造人..." << endl;
		builder->build_head();
		builder->build_body();
		builder->build_arms();
		builder->build_legs();
		builder->build_private_part();
	}

private:
	Builder* builder;
};

void test_01()
{
	// build man
	Builder* builder = new ManBuilder;
	NuWa* nw = new NuWa(builder);
	nw->Create();

	delete builder;
	delete nw;

	cout << "*****************" << endl;

	// build woman
	builder = new WomanBuilder;
	nw = new NuWa(builder);
	nw->Create();

	delete builder;
	delete nw;
}

int main(int argc, char* argv[])
{
	test_01();
	
	system("pause");
	return 0;	
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值