设计模式 - Factory Method

意图:定义一个用于创建对象的接口,让子类决定实例化哪一个类,使一个类的实例化延迟到其子类。

class Product
{
public:
    Product()
    {}
    virtual ~Product()
    {}
};

class ConcreteProductA: public Product
{
public:
    ConcreteProductA()
    {}
    ~ConcreteProductA()
    {}
};

class ConcreteProductB: public Product
{
public:
    ConcreteProductB()
    {}
    ~ConcreteProductB()
    {}
};

class Factory
{
public:
    Factory()
    {}
    virtual ~Factory()
    {}
    virtual Product* CreateProduct(int idx) = 0;
};

class ConcreteFactory: public Factory
{
public:
    ConcreteFactory()
    {}
    ~ConcreteFactory()
    {}
    Product* CreateProduct(int idx)
    {
        switch(idx)
        {
        case 1:
            return new ConcreteProductA();
        case 2:
            return new ConcreteProductB();
        default:
            return NULL;
        }
    }
};

 

posted @ 2013-05-04 20:21  Leung文  阅读(127)  评论(0编辑  收藏  举报