C++设计模式之建造者模式(Builder)
时间:2021-02-17 14:07:01|栏目:C代码|点击: 次
建造者模式与工厂模式最大的区别在与建造者模式更注重的是创建的一系列过程,如流水化作业,工厂模式强调的是区分不同的工厂和产品,而建造者模式更注重的统一不同产品在流水线上的工序,达到统一作业。
作用
建造者模式是将一个复杂对象和他的构造和组装过程分离,这样再重复创建不同对象时使用相同的流程进行建造。对于调用者来说,只需要知道产品的类型,而不需要知道具体的组装过程。
类视图
代码实现
class Builder { public: virtual void SelectCpu()= 0; virtual void SelectMatherboard() = 0; virtual void SelectMem() = 0; virtual void SelectDisk() = 0; virtual void SelectPower() = 0; virtual void SelectShell() = 0; }; //构造PC class PCBuilder : public Builder { public: void SelectCpu() { cout<<"Select PC Cpu"<<endl; } void SelectMatherboard() { cout<<"Select PC Matherboard"<<endl; } void SelectMem() { cout<<"Select PC Mem"<<endl; } void SelectDisk() { cout<<"Select PC Disk"<<endl; } void SelectPower() { cout<<"Select PC Power"<<endl; } void SelectShell() { cout<<"Select PC Shell"<<endl; } }; //构造Notebook class NoteBookBuilder : public Builder { public: void SelectCpu() { cout<<"Select NoteBook Cpu"<<endl; } void SelectMatherboard() { cout<<"Select NoteBook Matherboard"<<endl; } void SelectMem() { cout<<"Select NoteBook Mem"<<endl; } void SelectDisk() { cout<<"Select NoteBook Disk"<<endl; } void SelectPower() { cout<<"Select NoteBook Power"<<endl; } void SelectShell() { cout<<"Select NoteBook Shell"<<endl; } }; //构造的指挥官 class Director { private: Builder *m_pBuilder; public: Director(Builder *builder) { m_pBuilder = builder; } void Create(){ m_pBuilder->SelectCpu(); m_pBuilder->SelectMatherboard(); m_pBuilder->SelectMem(); m_pBuilder->SelectDisk(); m_pBuilder->SelectPower(); m_pBuilder->SelectShell(); } }; //调用 int main() { NoteBookBuilder thin; Director director(&thin); director.Create(); return 0; }