Factory 模式
用户不关心工厂的具体类型,只知道这是一个工厂就行。
通过工厂的实现推迟到子类里面去来确定工厂的具体类型。
工厂的具体类型来确定生产的具体产品。
同时用户不关心这是一个什么样子的产品,只知道这是一个产品
1 #ifndef _FACTORY_H_ 2 #define _FACTORY_H_ 3 4 #include "product.h" 5 class Factory 6 { 7 public: 8 virtual ~Factory(); 9 virtual Product* createProduct(); 10 protected: 11 Factory(); 12 private: 13 }; 14 15 class ConcreteFactory : public Factory 16 { 17 public: 18 ConcreteFactory(); 19 ~ConcreteFactory(); 20 Product* createProduct(); 21 protected: 22 private: 23 }; 24 25 #endif //_FACTORY_H_
1 #include "factory.h" 2 #include "product.h" 3 4 Factory::~Factory() 5 { 6 7 } 8 9 Factory::Factory() 10 { 11 12 } 13 14 Product* Factory::createProduct() 15 { 16 } 17 18 ConcreteFactory::ConcreteFactory() 19 { 20 21 } 22 23 ConcreteFactory::~ConcreteFactory() 24 { 25 26 } 27 28 Product* ConcreteFactory::createProduct() 29 { 30 return new ConcreteProduct(); 31 }
1 #ifndef _PRODUCT_H_ 2 #define _PRODUCT_H_ 3 4 class Product 5 { 6 public: 7 virtual ~Product(); 8 protected: 9 Product(); 10 private: 11 }; 12 13 class ConcreteProduct : public Product 14 { 15 public: 16 ConcreteProduct(); 17 ~ConcreteProduct(); 18 protected: 19 private: 20 }; 21 22 #endif //_PRODUCT_H_
1 #include "product.h" 2 #include <stdio.h> 3 Product::~Product() 4 { 5 6 } 7 8 Product::Product() 9 { 10 11 } 12 13 ConcreteProduct::ConcreteProduct() 14 { 15 printf("hello I'm product "); 16 } 17 18 ConcreteProduct::~ConcreteProduct() 19 { 20 }
1 #include "factory.h" 2 #include "product.h" 3 #include <stdio.h> 4 5 int main() 6 { 7 Product* pro = NULL; 8 Factory* fac = new ConcreteFactory(); 9 if(fac) 10 pro = fac->createProduct(); 11 return 0; 12 }