C++工場方法
3147 ワード
Singleton.h
ObjectFactory.h
Main.cpp
#pragma once
#ifndef SINGLETON_H
#define SINGLETON_H
template<class T>
class Singleton
{
public:
static T& Instance();
protected:
Singleton(){}
virtual ~Singleton(){}
/**
*
*/
private:
Singleton(const Singleton &);
Singleton & operator = (const Singleton &);
};
template<class T>
T& Singleton<T>::Instance()
{
/** */
static T instance;
return instance;
}
#endif
ObjectFactory.h
/**--------------------------------
* (Object Factory)
*
* Code by XadillaX
* http://www.xcoder.in
* Created at 2010-11-17 1:33
*/
#ifndef OBJECTFACTORY_H
#define OBJECTFACTORY_H
#pragma once
#include <map>
#include <string>
#include "Singleton.h"
template<class T>
class ObjectFactory : public Singleton<ObjectFactory<T>>
{
public:
typedef T* (*tCreator)(); ///<
typedef std::map<std::string, tCreator> tCreatorMap; ///< map
/**
* @brief " "
*
*
* @param *name
* @param procedure " "
* @return
*/
bool Register(char *type, tCreator procedure);
/**
* @brief " "
*
*
* @param &type
* @return
*/
T* Create(const std::string &type);
private:
/** " " */
tCreatorMap _map;
};
template<class T>
bool ObjectFactory<T>::Register(char *type, tCreator procedure)
{
string tmp(type);
/** map */
_map[tmp] = procedure;
return _map[tmp];
}
template<class T>
T* ObjectFactory<T>::Create(const std::string &type)
{
/** " " */
tCreatorMap::iterator iter = _map.find(type);
/** " " */
if(iter != _map.end())
{
/** " " */
tCreator r = iter->second;
/** " " */
return r();
}
return 0;
}
#endif
Main.cpp
#include <iostream>
#include "ObjectFactory.h"
using namespace std;
/** */
class Base;
/** Base */
typedef ObjectFactory<Base> BaseFactory;
class Base
{
public:
Base(){};
~Base(){};
};
class A : public Base
{
public:
A(){ cout << "A object created." << endl; };
~A(){};
static Base* ACreator()
{
return new A();
};
};
class B : public Base
{
public:
B(){ cout << "B object Created." << endl; }
~B();
static Base* BCreator()
{
return new B();
}
};
/**
* @brief
*/
int main()
{
/** A、B " " */
bool AFlag = BaseFactory::Instance().Register("A", A::ACreator);
bool BFlag = BaseFactory::Instance().Register("B", B::BCreator);
/** */
if(!AFlag || !BFlag) exit(0);
Base *p;
for(int i = 0; i < 10; i++)
{
string type = (i % 2) ? string("A") : string("B");
/** p " " */
p = BaseFactory::Instance().Create(type);
delete p;
}
return 0;
}