解释说明:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
UML 结构图:
抽象建造者(Builder):这个接口规定要实现复杂对象的那些部分的创建,并不设计具体部件对象的创建
具体建造者(ConcreteBuilder):实现 Builder 的接口,完成复杂产品的各个部件的具体创建方法。在构造过程完成后,提供产品的实例
产品(Product):要创建的复杂对象
指挥者(Director):调用具体建造者来创建复杂对象的各个部分,在指导者中不涉及具体产品的信息,只负责保证对象各部分完整创建或按照某种顺序创建
优点:
建造者独立,易于扩展
便于控制细节风险
缺点:
产品必须有共同点,范围有限制
如果内部变化复杂,将会有很多的建造类
适用场景
需要生成的对象具有复杂的内部结构
需要生成的对象内部属性本身相互依赖
考虑这样一个场景,如下图:
Jungle想要建造一栋简易的房子(地板、墙和天花板),两个工程师带着各自的方案找上门来,直接给Jungle看方案和效果图。犹豫再三,Jungle最终选定了一位工程师……交房之日,Jungle满意的看着建好的房子,开始思考:这房子究竟是怎么建成的呢?这地板、墙和天花板是怎么建造的呢?工程师笑着说:“It's none of your business”
void SetmCpu(string cpu) { m_strCpu = cpu; }
void SetmMainboard(string mainboard) { m_strMainboard = mainboard; }
void SetmRam(string ram) { m_strRam = ram; }
void SetVideoCard(string videoCard) { m_strVideoCard = videoCard; }
string GetCPU() { return m_strCpu; }
string GetMainboard() { return m_strMainboard; }
string GetRam() { return m_strRam; }
string GetVideoCard() { return m_strVideoCard; }
virtual void BuildCpu() = 0;
virtual void BuildMainboard() = 0;
virtual void BuildRam() = 0;
virtual void BuildVideoCard() = 0;
virtual Computer* GetResult() = 0;
class ThinkPadBuilder : public IBuilder
ThinkPadBuilder() { m_pComputer = new Computer(); }
void BuildCpu() { m_pComputer->SetmCpu("i5-6200U"); }
void BuildMainboard() { m_pComputer->SetmMainboard("Intel DH57DD"); }
void BuildRam() { m_pComputer->SetmRam("DDR4"); }
void BuildVideoCard() { m_pComputer->SetVideoCard("NVIDIA Geforce 920MX"); }
Computer* GetResult() { return m_pComputer; }
class YogaBuilder : public IBuilder
YogaBuilder() { m_pComputer = new Computer(); }
void BuildCpu() { m_pComputer->SetmCpu("i7-7500U"); }
void BuildMainboard() { m_pComputer->SetmMainboard("Intel DP55KG"); }
void BuildRam() { m_pComputer->SetmRam("DDR5"); }
void BuildVideoCard() { m_pComputer->SetVideoCard("NVIDIA GeForce 940MX"); }
Computer* GetResult() { return m_pComputer; }
void Create(IBuilder* builder) {
builder->BuildMainboard();
builder->BuildVideoCard();
#define SAFE_DELETE(p) { if(p){delete(p); (p)=NULL;} }
Direcror* pDirecror = new Direcror();
ThinkPadBuilder* pTPBuilder = new ThinkPadBuilder();
YogaBuilder* pYogaBuilder = new YogaBuilder();
pDirecror->Create(pTPBuilder);
pDirecror->Create(pYogaBuilder);
Computer* pThinkPadComputer = pTPBuilder->GetResult();
Computer* pYogaComputer = pYogaBuilder->GetResult();
cout << "-----ThinkPad-----" << endl;
cout << "CPU: " << pThinkPadComputer->GetCPU() << endl;
cout << "Mainboard: " << pThinkPadComputer->GetMainboard() << endl;
cout << "Ram: " << pThinkPadComputer->GetRam() << endl;
cout << "VideoCard: " << pThinkPadComputer->GetVideoCard() << endl;
cout << "-----Yoga-----" << endl;
cout << "CPU: " << pYogaComputer->GetCPU() << endl;
cout << "Mainboard: " << pYogaComputer->GetMainboard() << endl;
cout << "Ram: " << pYogaComputer->GetRam() << endl;
cout << "VideoCard: " << pYogaComputer->GetVideoCard() << endl;
SAFE_DELETE(pThinkPadComputer);
SAFE_DELETE(pYogaComputer);
SAFE_DELETE(pYogaBuilder);