程序员人生 网站导航

Factory Pattern(工厂模式)

栏目:综合技术时间:2015-06-06 08:06:45

Factory Pattern(C++实现)

/*Product.h*/ #ifndef PRODUCT_H #define PRODUCT_H class Product { public: virtual ~Product()=0; protected: Product(); private: }; class ConcreteProduct:public Product { public: ~ConcreteProduct(); ConcreteProduct(); protected: private: }; #endif

/*Product.cpp*/ #include "Product.h" #include <iostream> Product::Product() { } Product::~Product() { } ConcreteProduct::ConcreteProduct() { std::cout<<"ConcreteProduct..."<<std::endl; } ConcreteProduct::~ConcreteProduct() { }

/*Factory.h*/ #ifndef FACTORY_H #define FACTORY_H class Product; class Factory { public: virtual ~Factory()=0; virtual Product *CreateProduct()=0; protected: Factory(); private: }; class ConcreteFactory:public Factory { public; ~ConcreteFactory(); ConcreteFactory(); Product *CreateProduct(); protected: private: }; #endif

/*Factory.cpp*/ #include "Factory.h" #include "Product.h" #include <iostream> Factory::Factory() { } Factory::~Factory() { } ConcreteFactory::ConcreteFactory() { std::cout<<"ConcreteFactory..."<<std::endl; } ConcreteFactory::~ConcreteFactory() { } Product *ConcreteFactory::CreateProduct() { return new ConcreteProduct(); }
/*main.cpp*/ #include "Factory.h" #include "Product.h" #include <iostream> int main() { Factory *fac=new ConcreteFactory(); Product *p=fac->CreateProduct(); return 0; }



------分隔线----------------------------
------分隔线----------------------------

最新技术推荐