C++

程序设计模式(三)Builder

每天一个设计模式

Posted by VK on February 4, 2020

程序设计模式(三)Builder

#include <iostream>
using namespace std;

class Product{
public:
	Product(){}
	~Product(){}
	void setPartA(const string &s){ this->m_PartA = s;};
	void setPartB(const string &s){ this->m_PartB = s;};
	void setPartC(const string &s){ this->m_PartC = s;};

private:
	string m_PartA;
	string m_PartB;
	string m_PartC;
};

class Builder{
public:
	Builder(){}
	virtual ~Builder(){}
	virtual void BuildPartA() = 0;
	virtual void BuildPartB() = 0;
	virtual void BuildPartC() = 0;
	virtual Product *GetProduct() = 0;
};

class ConcreteBuilder1:public Builder
{
public:
	ConcreteBuilder1();
	~ConcreteBuilder1();
	virtual void BuildPartA();
	virtual void BuildPartB();
	virtual void BuildPartC();
	virtual Product*GetProduct();
private:
	Product* m_pProduct;	
};

class ConcreteBuilder2:public Builder
{
public:
	ConcreteBuilder2();
	~ConcreteBuilder2();
	virtual void BuildPartA();
	virtual void BuildPartB();
	virtual void BuildPartC();
	virtual Product*GetProduct();
private:
	Product* m_pProduct;	
};


class Director
{
public:
	Director(Builder*pBuilder);
	~Director();

	void Construct();

private:
	Builder *m_pBuilder;
};


ConcreteBuilder1::ConcreteBuilder1(){
	this->m_pProduct = new Product();
	cout<<"Create empty product!"<<endl;
}


ConcreteBuilder1::~ConcreteBuilder1()
{
	delete m_pProduct;
	this->m_pProduct = NULL;
}

void ConcreteBuilder1::BuildPartA()
{
	m_pProduct->setPartA("A");
	cout<<"BuildPartA"<<endl;
}


void ConcreteBuilder1::BuildPartB()
{
	m_pProduct->setPartB("B");
	cout<<"BuildPartB"<<endl;
}


void ConcreteBuilder1::BuildPartC()
{
	m_pProduct->setPartC("C");
	cout<<"BuildPartC"<<endl;
}

Product *ConcreteBuilder1::GetProduct(){
	return m_pProduct;
}


ConcreteBuilder2::ConcreteBuilder2(){
	this->m_pProduct = new Product();
	cout<<"Create empty product!"<<endl;
}


ConcreteBuilder2::~ConcreteBuilder2()
{
	delete m_pProduct;
	this->m_pProduct = NULL;
}

void ConcreteBuilder2::BuildPartA()
{
	m_pProduct->setPartA("A");
	cout<<"BuildPartA"<<endl;
}


void ConcreteBuilder2::BuildPartB()
{
	m_pProduct->setPartB("B");
	cout<<"BuildPartB"<<endl;
}


void ConcreteBuilder2::BuildPartC()
{
	m_pProduct->setPartC("C");
	cout<<"BuildPartC"<<endl;
}

Product *ConcreteBuilder2::GetProduct(){
	return m_pProduct;
}


Director::Director(Builder*pBuilder){
	m_pBuilder = pBuilder;
}

Director::~Director()
{
	delete m_pBuilder;
	m_pBuilder = NULL;
}

void Director::Construct()
{
	m_pBuilder->BuildPartA();
	m_pBuilder->BuildPartB();
	m_pBuilder->BuildPartC();
}

int main()
{
	Director* pDirector1 = new Director(new ConcreteBuilder1());
	pDirector1->Construct();

	Director* pDirector2 = new Director(new ConcreteBuilder2());
	pDirector2->Construct();
	return 0;
}