首页 > 代码库 > Abstract_Factory

Abstract_Factory

#include <iostream>using namespace std;#define DESTORY_POINTER(ptr) if (ptr) { delete ptr; ptr = NULL; }class ProductFamilyA{public:    virtual ~ProductFamilyA() {}    virtual void Action()=0;    protected:    ProductFamilyA() {}};class ProductFamilyB{public:    virtual ~ProductFamilyB() {}    virtual void Action()=0;    protected:    ProductFamilyB() {}};class Factory{public:    virtual ~Factory() {}    virtual ProductFamilyA* CreateProductA()=0;    virtual ProductFamilyB* CreateProductB()=0;protected:    Factory() {}};class ProductA1 : public ProductFamilyA{public:    ProductA1() {}    void Action() { cout<<"ProductFamilyA->ProductA1::Action"<<endl; }};class ProductA2 : public ProductFamilyA{public:    ProductA2() {}    void Action() { cout<<"ProductFamilyA->ProductA2::Action"<<endl; }};class ProductB1 : public ProductFamilyB{public:    ProductB1() {}    void Action() { cout<<"ProductFamilyB->ProductB1::Action"<<endl; }};class ProductB2 : public ProductFamilyB{public:    ProductB2() {}    void Action() { cout<<"ProductFamilyB->ProductB2::Action"<<endl; }};class Factory1 : public Factory{public:    ProductFamilyA* CreateProductA() { return new ProductA1; }    ProductFamilyB* CreateProductB() { return new ProductB1; }};class Factory2 : public Factory{public:    ProductFamilyA* CreateProductA() { return new ProductA2; }    ProductFamilyB* CreateProductB() { return new ProductB2; }};int main(int argc, char *argv[]){    Factory* pFactory = NULL;    ProductFamilyA* pProductFamilyA = NULL;    ProductFamilyB* pProductFamilyB = NULL;    pFactory = new Factory1;    pProductFamilyA = pFactory->CreateProductA();    pProductFamilyB = pFactory->CreateProductB();    pProductFamilyA->Action();    pProductFamilyB->Action();        DESTORY_POINTER(pFactory);    DESTORY_POINTER(pProductFamilyA);    DESTORY_POINTER(pProductFamilyB);        pFactory = new Factory2;    pProductFamilyA = pFactory->CreateProductA();    pProductFamilyB = pFactory->CreateProductB();    pProductFamilyA->Action();    pProductFamilyB->Action();        DESTORY_POINTER(pFactory);    DESTORY_POINTER(pProductFamilyA);    DESTORY_POINTER(pProductFamilyB);        return 0;}

 

Abstract_Factory