Design Pattern --- Abstract Factory

/*
 *        ProductA.
 */
class ProductA {};
class Product1_A : public ProductA 
{
public:
    Product1_A() { cout <<"Product1_A" <<endl; } ////
};                                                 //  
class Product2_A : public ProductA                 //
{                                                  //
public:                                            //
    Product2_A() { cout <<"Product2_A" <<endl; } ////////
};                                                 //  //
                                                   //  //
/*                                                 ///////// Series 1.
 *        ProductB.                                //  //
 */                                                //  //
class ProductB {};                                 //  //
class Product1_B : public ProductB                 //  //
{                                                  //  ////////// Series 2.
public:                                            //  //
    Product1_B() { cout <<"Product1_B" <<endl; } ////  //
};                                                     //
class Product2_B : public ProductB                     // 
{                                                      // 
public:                                                // 
    Product2_B() { cout <<"Product2_B" <<endl; } ////////
};

class Factory
{
public:
    // Interface.
    virtual ProductA *CreateProductA() = 0;    // Just create a product A. Maybe either series1 or series2.
    virtual ProductB *CreateProductB() = 0;    // Same on.
};
/*
 *        Create series 1.
 */
class Factory1 : public Factory
{
public:
    // Interface.
    virtual ProductA *CreateProductA() override { return new Product1_A; }
    virtual ProductB *CreateProductB() override { return new Product1_B; }
};
/*
 *        Create series 2.
 */
class Factory2 : public Factory
{
public:
    // Interface.
    virtual ProductA *CreateProductA() override { return new Product2_A; }
    virtual ProductB *CreateProductB() override { return new Product2_B; }
};

int main(int argc, char *argv[])
{
    Factory *f = new Factory1;        // new Factory2;
    ProductA *pA = f->CreateProductA();
    ProductB *pB = f->CreateProductB();

    // TODO: Release memory.

    return 0;
}

  适用于类成分相同, 但是属于不同的系统。例如:windows 和 linux 的窗口应用程序组件。

  此模式就像笛卡尔积一样, 使用一个抽象的工厂, 交叉的创建了某一系列的所有组件.

posted @ 2013-01-17 10:47  walfud  阅读(113)  评论(0编辑  收藏  举报