今天来学习一下建造者模式,下面看一下C++代码的实现。
#include <iostream>
#include <string>
#include <string.h>
#include <list>
#include <math.h>
#include <stdlib.h>
using namespace std;
//建造者模式
class Product //具体产品
{
public:
Product()
{
parts = new list<string>;
}
void add(string part)
{
parts->push_back(part);
}
void Show()
{
cout << "Product Show" << endl;
list<string>::iterator itor;
itor = parts->begin();
while(itor != parts->end())
{
cout<< *itor++ <<endl;
}
}
private:
list<string> *parts;
};
class Builder //Builder是为创建一个Product对象的各个部件指定的抽象接口
{
public:
virtual void BuildPartA()
{
cout << "Builder BuildPartA" << endl;
}
virtual void BuildPartB()
{
cout << "Builder BuildPartB" << endl;
}
virtual Product* GetResult()
{
return new Product();
}
};
class ConBuilder1 : public Builder //具体的建造对象
{
public:
ConBuilder1()
{
pro = new Product();
}
void BuildPartA()
{
cout << "ConBuilder1 BuildPartA" << endl;
}
void BuildPartB()
{
cout << "ConBuilder1 BuildPartB" << endl;
}
private:
Product *pro;
};
class ConBuilder2 : public Builder //具体的建造对象
{
public:
ConBuilder2()
{
product = new Product();
}
void BuildPartA()
{
cout << "ConBuilder2 BuildPartB" << endl;
}
void BuildPartB()
{
cout << "ConBuilder2 BuildPartB" << endl;
}
private:
Product *product;
};
class Director //指挥类,指挥建造
{
public:
void Construct(Builder *builder)
{
builder->BuildPartA(); //建造A部分
builder->BuildPartB(); //建造B部分
}
};
int main()
{
Director *director = new Director();
Builder *b1 = new ConBuilder1();
Builder *b2 = new ConBuilder2();
director->Construct(b1);
Product *p1 = b1->GetResult();
p1->Show();
director->Construct(b2);
Product *p2 = b2->GetResult();
p2->Show();
delete director;
delete b1;
delete b2;
delete p1;
delete p2;
return 0;
}
建造者模式定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
上述代码中,ConBuilder1和ConBuilder2是具体的建造对象,里面有具体的建造方法,但是ConBuilder1和ConBuilder2中相同的建造方法的实现又不一样。该产品的构建在Director类中,表示在product类中,做到了对象的构建与表示分离。在客户端中,用户只需要建造的类型就可以得到他们,不需要知道具体的建造细节。在ConBuilder1和ConBuilder2中,BuildPartA和BuildPartB都是固定的,就是大致建造过程是这样,具体的实现会有一些差异。
适用场景:用于创建一些复杂的对象,这些对象内部建造顺序通常是固定的,但内部对象通过面临复杂的变化。