设计模式8——建造者模式
建造者模式定义一个具体的物体,是各种属性的集合。要创建该物体时,可以构建一个构造器,该构造器包含特定的构造方式,但是只提供一个接口,具体构造细节放在派生类中实现。
Builder.h内容
1 #ifndef Builder_H_H 2 #define Builder_H_H 3 4 #include <iostream> 5 #include <string> 6 #include <vector> 7 using namespace std; 8 9 class Product 10 { 11 public: 12 Product() {} 13 void display(){ 14 //cout << vecStr.size() << endl; 15 for(size_t i=0; i<vecStr.size(); ++i){ 16 cout << vecStr[i] << " "; 17 } 18 cout << endl; 19 } 20 void addItem(string str) { vecStr.push_back(str); } 21 private: 22 vector<string> vecStr; 23 }; 24 25 class Builder 26 { 27 public: 28 Builder() {} 29 virtual Product* getProduct() = 0; 30 void Build(){ 31 buildItem1(); 32 buildItem2(); 33 } 34 virtual void buildItem1() = 0; 35 virtual void buildItem2() = 0; 36 virtual ~Builder() {} 37 }; 38 39 40 class BuilderOne : public Builder 41 { 42 public: 43 BuilderOne() { product = new Product(); } 44 virtual void buildItem1() { product->addItem("First"); } 45 virtual void buildItem2() { product->addItem("Second"); } 46 virtual Product* getProduct() { return product; } 47 void release(){ 48 if(product != NULL){ 49 delete product; 50 product = NULL; 51 } 52 } 53 virtual ~BuilderOne() { release(); } 54 private: 55 Product *product; 56 }; 57 58 class BuilderTwo : public Builder 59 { 60 public: 61 BuilderTwo() { product = new Product(); } 62 virtual void buildItem1() { product->addItem("A"); } 63 virtual void buildItem2() { product->addItem("B"); } 64 virtual Product* getProduct() { return product; } 65 void release(){ 66 if(product != NULL){ 67 delete product; 68 product = NULL; 69 } 70 } 71 virtual ~BuilderTwo() { release(); } 72 private: 73 Product *product; 74 }; 75 76 class Direct 77 { 78 public: 79 Direct() : builder(NULL) {} 80 void setBuilder(Builder *builder0){ 81 release(); 82 builder = builder0; 83 } 84 void Build(){ 85 builder->Build(); 86 } 87 Product* getProduct() { return builder->getProduct(); } 88 void release(){ 89 if(builder != NULL){ 90 delete builder; 91 builder = NULL; 92 } 93 } 94 ~Direct() { release(); } 95 private: 96 Builder *builder; 97 }; 98 99 void BuilderTest() 100 { 101 Builder *builder1 = new BuilderOne(); 102 Builder *builder2 = new BuilderTwo(); 103 Direct *direct = new Direct(); 104 105 direct->setBuilder(builder1); 106 direct->Build(); 107 direct->getProduct()->display(); 108 109 direct->setBuilder(builder2); 110 direct->Build(); 111 direct->getProduct()->display(); 112 113 delete direct; 114 } 115 116 #endif
运行结果: