⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 factory.h

📁 介绍c++游戏编程
💻 H
字号:


#ifndef FACTORY_H_
#define FACTORY_H_

#pragma warning (disable : 4786)  

#include <map>
#include <string>


typedef std::string ObjectType;


template<class Base>
class CreatorBase
{
public:
    virtual ~CreatorBase() {}
    virtual Base * Create() const = 0;
};



template<class Product, class Base>
class Creator : public CreatorBase<Base>
{
public:
    virtual Base * Create() const {return new Product;}
};




template<class Base>
class Factory
{
public:
    Base * Create(ObjectType type);
    bool Register(ObjectType type, CreatorBase<Base> * pCreator);
private:
    typedef std::map<ObjectType, CreatorBase<Base> *> CreatorMap;
    CreatorMap m_creatorMap;
};


template<class Base>
bool Factory<Base>::Register(ObjectType type, CreatorBase<Base> * pCreator)
{
    CreatorMap::iterator it = m_creatorMap.find(type);
    if (it != m_creatorMap.end()) {
        delete pCreator;
        return false;
    }
    m_creatorMap[type] = pCreator;
    return true;
}


template<class Base>
Base * Factory<Base>::Create(ObjectType type)
{
    CreatorMap::iterator it = m_creatorMap.find(type);
    if (it == m_creatorMap.end()) 
        return NULL;

    CreatorBase<Base> * pCreator = (*it).second;
    return pCreator->Create();
}



#endif

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -