码迷,mamicode.com
首页 > 其他好文 > 详细

Factory_Method

时间:2014-12-08 13:47:41      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   ar   color   os   sp   div   log   

class Product
{
public:
    virtual ~Product() {}
    virtual void DoSomething()=0;
};


class ProductA : public Product
{
public:
    ProductA() {}
    ~ProductA() {}

    virtual void DoSomething();
};

class ProductB : public Product
{
public:
    ProductB() {}
    ~ProductB() {}

    virtual void DoSomething();
};

class ProductC : public Product
{
public:
    ProductC() {}
    ~ProductC() {}

    virtual void DoSomething();
};




void ProductA::DoSomething()
{
    cout<<"ProductA::DoSomething"<<endl;
}

void ProductB::DoSomething()
{
    cout<<"ProductB::DoSomething"<<endl;
}

void ProductC::DoSomething()
{
    cout<<"ProductC::DoSomething"<<endl;
}


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

class FactoryA : public Factory
{
public:
    FactoryA() {}
    virtual ~FactoryA() {}
    virtual Product* CreateProduct();
};

class FactoryB : public Factory
{
public:
    FactoryB() {}
    virtual ~FactoryB() {}
    virtual Product* CreateProduct();
};

class FactoryC : public Factory
{
public:
    FactoryC() {}
    virtual ~FactoryC() {}
    virtual Product* CreateProduct();
};

Product* FactoryA::CreateProduct()
{
    return new ProductA;
}

Product* FactoryB::CreateProduct()
{
    return new ProductB;
}

Product* FactoryC::CreateProduct()
{
    return new ProductC;
}



#define DESTROY(ptr) if (ptr) { delete ptr; ptr = NULL; }


int main(int argc, char *argv[])
{
    Factory* pFactory = NULL;
    Product* pProduct = NULL;

    pFactory = new FactoryA;
    pProduct = pFactory->CreateProduct();
    pProduct->DoSomething();

    DESTROY(pFactory);
    DESTROY(pProduct);

    pFactory = new FactoryB;
    pProduct = pFactory->CreateProduct();
    pProduct->DoSomething();

    DESTROY(pFactory);
    DESTROY(pProduct);

    pFactory = new FactoryC;
    pProduct = pFactory->CreateProduct();
    pProduct->DoSomething();

    DESTROY(pFactory);
    DESTROY(pProduct);

    return 0;
}

 

Factory_Method

标签:des   style   blog   ar   color   os   sp   div   log   

原文地址:http://www.cnblogs.com/stanley198610281217/p/4150749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!