工厂方法模式(Factory Method Pattern)
1 #ifndef FACTORYMETHOD_H 2 #define FACTORYMETHOD_H 3 4 #include<iostream> 5 using namespace std; 6 7 class Product//should be a pure virtual class. 8 { 9 public: 10 Product(){} 11 ~Product(){} 12 }; 13 14 class ConcreteProductA:public Product 15 { 16 public: 17 ConcreteProductA() 18 { 19 cout<<"ConcreteProductA is created."<<endl; 20 } 21 }; 22 23 class ConcreteProductB:public Product 24 { 25 public: 26 ConcreteProductB() 27 { 28 cout<<"ConcreteProductB is created."<<endl; 29 } 30 }; 31 32 class Creator 33 { 34 public: 35 virtual Product* createProduct()=0; 36 }; 37 38 class ConcreteCreatorA:public Creator 39 { 40 public: 41 Product* createProduct() 42 { 43 return new ConcreteProductA(); 44 } 45 }; 46 47 class ConcreteCreatorB:public Creator 48 { 49 public: 50 Product* createProduct() 51 { 52 return new ConcreteProductB(); 53 } 54 }; 55 56 #endif//FACTORYMETHOD_H 57 58 int main() 59 { 60 Creator* creator=new ConcreteCreatorA(); 61 creator->createProduct(); 62 cout<<endl; 63 64 creator=new ConcreteCreatorB(); 65 creator->createProduct(); 66 67 return 0; 68 }