/*Product.h*/ #ifndef PRODUCT_H #define PRODUCT_H class AbstractProductA { public: virtual ~AbstractProductA(); protected: AbstractProductA(); private: }; class AbstractProductB { public: virtual ~AbstractProductB(); protected: AbstractProductB(); private: }; class ProductA1:public AbstractProductA { public: ProductA1(); ~ProductA1(); protected: private: }; class ProductA2:public AbstractProductA { public: ProductA2(); ~ProductA2(); protected: private: }; class ProductB1:public AbstractProductB { public: ProductB1(); ~ProductB1(); protected: private: }; class ProductB2:public AbstractProductB { public: ProductB2(); ~ProductB2(); protected: private: }; #endif
/*Product.cpp*/ #include "Product.h" #include <iostream> AbstractProductA::AbstractProductA() { } AbstractProductA::~AbstractProductA() { } AbstractProductB::AbstractProductB() { } AbstractProductB::~AbstractProductB() { } ProductA1::ProductA1() { std::cout<<"ProductA1..."<<std::endl; } ProductA1::~ProductA1() { } ProductA2::ProductA2() { std::cout<<"ProductA2..."<<std::endl; } ProductB1::ProductB1() { std::cout<<"ProductB1..."<<std::endl; } ProductB1::~ProductB1() { } ProductB2::ProductB2() { cout<<"ProductB2"<<std::endl; } ProductB2::~ProductB2() { }
/*AbstractFactory.h*/ #ifndef ABSTRACTFACTORY_H #define ABSTRACTFACTORY_H class AbstractProductA; class AbstractProductB; class AbstractFactory { public: virtual ~AbstractFactory(); virtual AbstractProductA *CreateProductA()=0; virtual AbstractProductB *CreateProductB()=0; protected: AbstractFactory(); private: }; class ConcreteFactory1:public AbstractFactory { public: ConcreteFactory1(); ~ConcreteFactory1(); AbstractProductA *CreateProductA(); AbstractProductB *CreateProductB(); protected: private: }; class ConcreteFactory2::public AbstractFactory { public: ConcreteFactory2(); ~ConcreteFactory2(); AbstractProductA *CreateProductA(); AbstractProductB *CreateProductB(); protected: private: }; #endif
/*AbstractFactory.cpp*/ #include "AbstractFactory.h" #include "Product.h" #include <iostream> AbstractFactory::AbstractFactory() { } AbstractFactory::~AbstractFactory() { } ConcreteFactory1::ConcreteFactory1() { } ConcreteFactory1::~ConcreteFactory1() { } AbstractProductA *ConcreteFactory1::CreateProductA() { return new ProductA1(); } AbstractProductB *ConcreteFactory1::CreateProductB() { return new ProductB1(); } ConcreteFactory2::ConcreteFactory2() { } ConcreteFactory2::~ConcreteFactory2() { } AbstractProductA *ConcreteFactory2::CreateProductA() { return new ProductA2(); } AbstractProductB *ConcreteFactory2::CreateProductB() { return new ProductB2(); }
/*main.cpp*/ #include "AbstractFactory.h" int main() { AbstractFactory *cf1=new ConcreteFactory1(); cf1->CreateProductA(); cf1->CreateProductB(); AbstractFactory *cf2=new ConcreteFactory2(); cf2->CreateProductA(); cf2->CreateProductB(); return 0; }
AbstractFactory Pattern(抽象工厂模式)
原文:http://blog.csdn.net/tlzhatao/article/details/45442161