1 #include <iostream> 2 using namespace std; 3 4 5 struct person{ 6 int head; 7 int body; 8 }; 9 class Builder 10 { 11 public: 12 virtual void BuildHead() {} 13 virtual void BuildBody() {} 14 virtual person* get()=0; 15 virtual ~Builder(){} 16 }; 17 //构造瘦人 18 class ThinBuilder : public Builder 19 { 20 public: 21 person * my; 22 ThinBuilder(){my=new person;} 23 virtual void BuildHead() { cout<<"build thin body"<<endl;my->body=3; } 24 virtual void BuildBody() { cout<<"build thin head"<<endl;my->head=5; } 25 virtual person* get(){return my;} 26 }; 27 28 29 //构造胖人 30 class fatBuilder : public Builder 31 { 32 public: 33 person * my; 34 fatBuilder(){my=new person;} 35 virtual void BuildHead() { cout<<"build thin body"<<endl;my->body=30; } 36 virtual void BuildBody() { cout<<"build thin head"<<endl;my->head=50; } 37 virtual person* get(){return my;} 38 }; 39 40 41 //构造的指挥官 42 class Director 43 { 44 private: 45 Builder *m_pBuilder; 46 public: 47 Director(Builder *builder) { m_pBuilder = builder; } 48 //两种create方法都可以,本质上是一样的 49 void Create(){ 50 m_pBuilder->BuildHead(); 51 m_pBuilder->BuildBody(); 52 } 53 54 person* create2(){ 55 m_pBuilder->BuildHead(); 56 m_pBuilder->BuildBody(); 57 return m_pBuilder->get(); 58 } 59 }; 60 int main() 61 { 62 ThinBuilder thin; 63 Director director(&thin); 64 director.Create(); 65 person* tmp = thin.get(); 66 cout << tmp->body << "\t" << tmp->head << endl; 67 delete tmp; 68 69 fatBuilder thin2; 70 Director director2(&thin2); 71 tmp = director2.create2(); 72 cout << tmp->body << "\t" << tmp->head << endl; 73 delete tmp; 74 return 0; 75 }