Factory模式具有两大重要的功能:
(1)、定义创建对象的接口,封装了对象的创建;
(2)、使具体化类工作延迟到了子类中。
//Product.h #ifndef _PRODUCT_H_ #define _PRODUCT_H_ class Product { public: virtual ~Product(); protected: Product(); private: }; class ConcreteProduct:public Product { public: ConcreteProduct(); ~ConcreteProduct(); protected: private: }; #endif //_PRODUCT_H_
//Product.cpp #include "Product.h" #include <iostream> using namespace std; Product::Product() {} Product::~Product() {} ConcreteProduct::ConcreteProduct() {} ConcreteProduct::~ConcreteProduct() {}
//Factory.h #ifndef _FACTORY_H_ #define _FACTORY_H_ class Product; class Factory { public: virtual ~Factory(); virtual Product *CreateProduct() = 0; protected: void Factory(); private: }; class ConcreteFactory:public Factory { public: ConcreteFactory(); ~ConcreteFactory(); Product * CreateProduct(); protected: private: }; #endif //_FACTORY_H_
//Fatory.cpp #include "Factory.h" #include "Product.h" #include <iostream> using namespace std; Factory::Factory() {} Factory::~Factory() {} ConcreteFactory::ConcreteFactory() {} ConcreteFactory::ConcreteFactory() {} Product ConcreteFactory::CreateProduct() { ConcreteProduct cproduct = new ConcreteProduct; return product; }
//main.cpp #include "Factory.h" #include "Product.h" #include <iostream> using namespace std; int main(int argc,char *argv[]) { Factory *fac = new ConcreteFactory; Product *p = fac->CreateProduct(); return 0; }