原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象.
涉及到对深复制浅复制的理解.
View Code
1 class Uncopyable 2 { 3 protected: 4 Uncopyable(){} 5 ~Uncopyable(){} 6 7 private: 8 Uncopyable(const Uncopyable&); 9 Uncopyable& operator=(const Uncopyable&); 10 }; 11 12 template<class T> 13 class ICloneable : private Uncopyable 14 { 15 public: 16 virtual T* Clone() = 0; 17 }; 18 19 #include <cstdlib> 20 #include <string> 21 class Prototype : public ICloneable<Prototype> 22 { 23 public: 24 Prototype():ch_(new char[10]), integer_(0) 25 { 26 memset(ch_, '\0', 10); 27 } 28 29 ~Prototype(){ if(ch_) delete ch_; ch_ = nullptr; } 30 31 virtual Prototype* Clone() 32 { 33 Prototype* pt = new Prototype; 34 pt->CopySelf(*this); 35 return pt; 36 } 37 38 void SetChar(char c) 39 { 40 *ch_ = c; 41 } 42 43 private: 44 void CopySelf(const Prototype& rhs) 45 { 46 strcpy_s(ch_, 10, rhs.ch_); 47 integer_ = rhs.integer_; 48 } 49 char* ch_; 50 int integer_; 51 }; 52 53 #include <memory> 54 using std::shared_ptr; 55 56 template<class T> 57 T* CreateInstance(ICloneable<T>* clone) 58 { 59 return clone->Clone(); 60 } 61 62 63 int main() 64 { 65 Prototype t1; 66 t1.SetChar('1'); 67 68 //Prototype t2(t1); 69 //Prototype t3 = t1; 70 shared_ptr<Prototype> t4(CreateInstance(&t1)); 71 t4->SetChar('2'); 72 }
建造者模式:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示.
建造者模式是当在创建复杂对象的算法应该独立于该对象的组成部分以及他的装配方式时适用的模式
建造者更重视产品建造时的逻辑顺序,但抽象工厂更重视生产出不同型号的产品,而不关心顺序.
View Code
1 #include <string> 2 #include <iostream> 3 using std::cout; 4 using std::endl; 5 using std::string; 6 class Car 7 { 8 public: 9 void SetWheel(const string& wheel) 10 { 11 wheel_ = wheel; 12 } 13 14 void SetBody(const string& body) 15 { 16 body_ = body; 17 } 18 19 void Show() 20 { 21 cout << "body:" << body_; 22 cout << "wheel:" << wheel_ << endl; 23 } 24 25 26 private: 27 string wheel_; 28 string body_; 29 }; 30 31 class CarBuilder{ 32 public: 33 virtual void BuilderBody() = 0; 34 virtual void BuilderWheel() = 0; 35 virtual Car GetCar() 36 { 37 return car_; 38 } 39 protected: 40 Car car_; 41 }; 42 43 44 class BMWBuilder : public CarBuilder 45 { 46 public: 47 virtual void BuilderBody(){ 48 car_.SetBody("BMWBody"); 49 } 50 virtual void BuilderWheel(){ 51 car_.SetWheel("BMWWheel"); 52 } 53 }; 54 55 class KIABuilder : public CarBuilder 56 { 57 public: 58 virtual void BuilderBody(){ 59 car_.SetBody("KIABody"); 60 } 61 virtual void BuilderWheel(){ 62 car_.SetWheel("KIAWheel"); 63 } 64 }; 65 66 class Director 67 { 68 public: 69 Director(CarBuilder* builder):builder_(builder) 70 { 71 } 72 Car BuildCar() 73 { 74 builder_->BuilderBody(); 75 builder_->BuilderWheel(); 76 return builder_->GetCar(); 77 } 78 79 private: 80 CarBuilder* builder_; 81 }; 82 83 int main() 84 { 85 BMWBuilder bmw; 86 KIABuilder kia; 87 Director d(&bmw); 88 Car c = d.BuildCar(); 89 c.Show(); 90 Director d2(&kia); 91 Car c2 = d2.BuildCar(); 92 c2.Show(); 93 return 0; 94 }