设计模式:builder模式

使用场景:当需要创建的实例非常复杂时,需要先创建每一个小部分,然后在组装起来

理解:区别于模板方法模式,核心方法一个是在父类中,一个是在另一个监管类中,本质类似

class Builder
{
public:
	virtual void head() = 0;
	virtual void body() = 0;
	virtual void tail() = 0;
};

class Director
{
	Builder* builder;
public:
	Director(Builder* builder)
	{
		this->builder = builder;
	}
	
	void construct()     //核心方法
        				 //先构造每一个小部分,然后组装
	{
		builder->head();  
		builder->body();
		builder->tail();
	}
};
class TestBuilder: public Builder
{
public:
	void head()
	{
		cout << "*******************" << endl;
	}
	
	void body()
	{
		cout << "  Body Body Body" << endl;
	}
	
	void tail()
	{
		cout << "+++++++++++++++++++" << endl;
	}
};

int main() 
{
	Builder* pBuilder = new TestBuilder();
	Director d(pBuilder);
	d.construct();
	return 0;
}

 

posted @ 2019-08-30 09:20  Yong_无止境  阅读(196)  评论(0编辑  收藏  举报