product,h:
#ifndef _PRODUCT_H_ #define _PRODUCT_H_ class AbstractProductA{ protected: AbstractProductA(); public: virtual ~AbstractProductA(); }; class AbstractProductB{ protected: AbstractProductB(); public: virtual ~AbstractProductB(); }; class ProductA1:public AbstractProductA{ public: ProductA1(); ~ProductA1(); }; class ProductA2:public AbstractProductA{ public: ProductA2(); ~ProductA2(); }; class ProductB1:public AbstractProductB{ public: ProductB1(); ~ProductB1(); }; class ProductB2:public AbstractProductB{ public: ProductB2(); ~ProductB2(); }; #endifproduct.cpp:
#include "product.h" #include <iostream> using namespace std; AbstractProductA::AbstractProductA(){ } AbstractProductA::~AbstractProductA(){ } AbstractProductB::AbstractProductB(){ } AbstractProductB::~AbstractProductB(){ } ProductA1::ProductA1(){ cout<<"ProductA1..."<<endl; } ProductA1::~ProductA1(){ } ProductA2::ProductA2(){ cout<<"ProductA2..."<<endl; } ProductA2::~ProductA2(){ } ProductB1::ProductB1(){ cout<<"ProductB1..."<<endl; } ProductB1::~ProductB1(){ } ProductB2::ProductB2(){ cout<<"ProductB2..."<<endl; } ProductB2::~ProductB2(){ }factory.h:
#ifndef _FACTORY_H_ #define _FACTORY_H_ class AbstractProductA; class AbstractProductB; class AbstractFactory{ public: virtual ~AbstractFactory()=0; virtual AbstractProductA* CreateProductA()=0; virtual AbstractProductB* CreateProductB()=0; protected: AbstractFactory(); }; class ConcreateFactory1:public AbstractFactory{ public: ~ConcreateFactory1(); ConcreateFactory1(); AbstractProductA* CreateProductA(); AbstractProductB* CreateProductB(); }; class ConcreateFactory2:public AbstractFactory{ public: ~ConcreateFactory2(); ConcreateFactory2(); AbstractProductA* CreateProductA(); AbstractProductB* CreateProductB(); }; #endiffactory.cpp:
#include "factory.h" #include "product.h" #include <iostream> using namespace std; AbstractFactory::AbstractFactory(){ } AbstractFactory::~AbstractFactory(){ } ConcreateFactory1::ConcreateFactory1(){ cout<<"ConcreateFactory1..."<<endl; } ConcreateFactory1::~ConcreateFactory1(){ } AbstractProductA* ConcreateFactory1::CreateProductA(){ return new ProductA1(); } AbstractProductB* ConcreateFactory1::CreateProductB(){ return new ProductB1(); } ConcreateFactory2::ConcreateFactory2(){ cout<<"ConcreateFactory2..."<<endl; } ConcreateFactory2::~ConcreateFactory2(){ } AbstractProductA* ConcreateFactory2::CreateProductA(){ return new ProductA1(); } AbstractProductB* ConcreateFactory2::CreateProductB(){ return new ProductB1(); }main.cpp:
#include "factory.h" #include "product.h" #include <iostream> using namespace std; int main(){ AbstractFactory *fac1=new ConcreateFactory1(); fac1->CreateProductA(); fac1->CreateProductB(); AbstractFactory *fac2=new ConcreateFactory2(); fac2->CreateProductA(); fac2->CreateProductB(); return 1; }
AbstractFactory模式,布布扣,bubuko.com
原文:http://blog.csdn.net/starcuan/article/details/20226625