简单工厂模式是最简单的工厂模式,一般用在只需要单一工厂,而且产品少,同一时间只需要创建单一产品的情况下。
1 enum ProductType{TypeA,TypeB,TypeC}; 2 3 class Product 4 { 5 public: 6 virtual void show() = 0; 7 virtual ~Product(){}; 8 }; 9 10 class ProductA:public Product 11 { 12 public: 13 void show() 14 { 15 cout<<"This is A"<<endl; 16 } 17 ProductA() 18 { 19 cout<<"Constructing ProductA"<<endl; 20 } 21 ~ProductA() 22 { 23 cout<<"Destructing ProductA"<<endl; 24 } 25 }; 26 27 class ProductB:public Product 28 { 29 public: 30 void show() 31 { 32 cout<<"This is B"<<endl; 33 } 34 ProductA() 35 { 36 cout<<"Constructing ProductB"<<endl; 37 } 38 ~ProductA() 39 { 40 cout<<"Destructing ProductB"<<endl; 41 } 42 }; 43 44 class ProductC:public Product 45 { 46 public: 47 void show() 48 { 49 cout<<"This is C"<<endl; 50 } 51 ProductA() 52 { 53 cout<<"Constructing ProductC"<<endl; 54 } 55 ~ProductA() 56 { 57 cout<<"Destructing ProductC"<<endl; 58 } 59 }; 60 61 class ProductFactory{ 62 public: 63 Product*CreateProduct(productType type) 64 { 65 switch(type) 66 { 67 case TypeA: 68 return new ProductA(); 69 case TypeB: 70 return new ProductB(); 71 72 case TypeC: 73 return new ProductC(); 74 75 default: 76 return nullptr; 77 } 78 } 79 };