Factory工厂模式

#include <iostream>
using namespace std;

//基类。
class Parent
{
public:
    virtual void Printf()=0;
};
class Child1 : public Parent
{
public:
    void Printf()
    {
        cout << "Child1::Printf()" << endl;
    }
};
class Child2 : public Parent
{
public:
    void Printf()
    {
        cout << "Child2::Printf()" << endl;
    }
};
class Child3 : public Parent
{
public:
    void Printf()
    {
        cout << "Child3::Printf()" << endl;
    }
};

//工厂类。
template<typename Type>
class DoWhatBase
{
public:
    virtual Type* GetBase() = 0;
};

template<typename Type>
class Dowhat : public DoWhatBase<Type>
{
public:
    Type* GetBase()
    {
        return new Type();
    }
};

int main()
{
    DoWhatBase<Child1> *q = new Dowhat<Child1>();
    Parent *p = q->GetBase();
    p->Printf();
    return 0;
}
//特点一:定义创建对象的接口。封装了对象的创建。
//特点二:使详细化类的工作延迟到子类中。
posted @ 2018-01-23 11:25  zhchoutai  阅读(110)  评论(0编辑  收藏  举报