首页 > 代码库 > 设计模式——建造者模式/生成器模式(C++实现)
设计模式——建造者模式/生成器模式(C++实现)
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 class STProduct 7 { 8 public: 9 void setA(string str) 10 { 11 m_a = str; 12 } 13 14 void setB(string str) 15 { 16 m_b = str; 17 } 18 19 void setC(string str) 20 { 21 m_c = str; 22 } 23 24 void Show() 25 { 26 cout<< "Product: "<< m_a<< "!\t"<< m_b<< "!\t"<< m_c<< endl; 27 } 28 29 private: 30 string m_a; 31 string m_b; 32 string m_c; 33 }; 34 35 class STBuilder 36 { 37 public: 38 STBuilder() 39 { 40 m_pstProduct = new STProduct(); 41 } 42 virtual ~STBuilder() 43 { 44 delete m_pstProduct; 45 } 46 47 virtual void BuildPartA() = 0; 48 virtual void BuildPartB() = 0; 49 virtual void BuildPartC() = 0; 50 51 virtual STProduct* GetResult() 52 { 53 return m_pstProduct; 54 } 55 56 STProduct* m_pstProduct; 57 }; 58 59 class STConcreteBuilder: public STBuilder 60 { 61 public: 62 virtual void BuildPartA() 63 { 64 m_pstProduct->setA("A Style"); 65 } 66 67 virtual void BuildPartB() 68 { 69 m_pstProduct->setB("B Style"); 70 } 71 72 virtual void BuildPartC() 73 { 74 m_pstProduct->setC("C Style"); 75 } 76 }; 77 78 class STDirector 79 { 80 public: 81 ~STDirector() 82 { 83 delete m_pstBuilder; 84 } 85 86 void SetBuilder(STBuilder* pstTmpBuilder) 87 { 88 m_pstBuilder = pstTmpBuilder; 89 } 90 91 STProduct* Construct() 92 { 93 m_pstBuilder->BuildPartA(); 94 m_pstBuilder->BuildPartB(); 95 m_pstBuilder->BuildPartC(); 96 97 return m_pstBuilder->GetResult(); 98 } 99 100 STBuilder* m_pstBuilder;101 };102 103 int main(int argc, char* argv[])104 {105 STBuilder* pstBuilder = new STConcreteBuilder();106 107 STDirector* pstDirector = new STDirector();108 pstDirector->SetBuilder(pstBuilder);109 110 STProduct* pstProduct = pstDirector->Construct();111 cout<< "Show.................."<< endl;112 pstProduct->Show();113 114 return 0;115 }116 //////////////////////////////////////117 [root@ ~/learn_code/design_pattern/10_builder]$ ./builder118 Show..................119 Product: A Style! B Style! C Style
参考:http://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/builder.html
设计模式——建造者模式/生成器模式(C++实现)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。