小步慢跑

 

一个简单的类厂 模版

类厂实现

#pragma once

#include <map>
#include <iostream>
using namespace std;

class CShape
{
public:
    CShape(void){};
    ~CShape(void){};
public:
    virtual  void SayHello() = 0;
};


class CRectangle:public CShape
{
public:
    virtual  void SayHello()
    {
        cout << " hello CRectangle "<<endl;
    }
};

class CCircle:public CShape
{
public:
    virtual  void SayHello()
    {
        cout << " hello CCircle "<<endl;
    }
};

class CTriangle:public CShape
{
public:
    virtual  void SayHello()
    {
        cout << " hello CTriangle "<<endl;
    }
};
//创建器接口
template<typename TBase>
class ICreator
{
public:
    virtual TBase* Create()  = 0;
};
//创建接口的实现
template<typename TBase,typename T>
class ICreatorImpl :public ICreator<TBase>
{
public:
    virtual TBase* Create()
    {
        return new T();
    }
};

//类工厂
template<typename T,typename ID>
class CFactory
{
    typedef map<ID,ICreator<T>*> MAP_ID_CREATOR;
public:
    T*   Create(ID id)
    {
        MAP_ID_CREATOR::iterator it = m_mapID2Creator.find(id);
        if (m_mapID2Creator.end() == it)
            return 0;
        ICreator<T>* pICreator = it->second;

        return pICreator->Create();
    }
public:
    template<typename TImpl>
    void Register(ID id)
    {
        ICreatorImpl<T,TImpl>* pICreator = new ICreatorImpl<T,TImpl>();
        m_mapID2Creator[id] = pICreator;
    }

    void UnRegister(ID id)
    {
        MAP_ID_CREATOR::iterator it = m_mapID2Creator.find(id);
        if (m_mapID2Creator.end() != it)
        {
            ICreatorImpl<T,TImpl>* pICreator = it->second;
            delete pICreator;
            
            m_mapID2Creator.erase(it);
        }
    }
private:
    MAP_ID_CREATOR m_mapID2Creator;
};

调用:

#include "Shap.h"

int main()
{
    CFactory<CShape,int> _factory;

    _factory.Register<CRectangle>(1);
    _factory.Register<CCircle>(2);
    _factory.Register<CTriangle>(3);

    CShape* pShap1 = _factory.Create(1);
    pShap1->SayHello();

    CShape* pShap2 = _factory.Create(2);
    pShap2->SayHello();

    
    CShape* pShap3 = _factory.Create(3);
    pShap3->SayHello();

    getchar();
    return 1;
}

posted on 2012-12-12 09:21 zaccheo 阅读(254) 评论(0)  编辑 收藏 引用 所属分类: C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

统计

常用链接

留言簿

随笔分类(23)

随笔档案(26)

文章分类(1)

文章档案(1)

csdn

搜索

最新评论

阅读排行榜

评论排行榜