建造者模式與工廠模式最大的區別在與建造者模式更注重的是創建的一系列過程,如流水化作業,工廠模式強調的是區分不同的工廠和產品,而建造者模式更注重的統一不同產品在流水線上的工序,達到統一作業。
作用
建造者模式是將一個復雜對象和他的構造和組裝過程分離,這樣再重復創建不同對象時使用相同的流程進行建造。對于調用者來說,只需要知道產品的類型,而不需要知道具體的組裝過程。
類視圖
代碼實現
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; }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答