頭文件:
/*整合模版,使得類的注冊(cè)和創(chuàng)建可以使用字符串,這樣能夠用于多語言編程環(huán)境(腳本引擎在底層的對(duì)象創(chuàng)建(直接使用字符串創(chuàng)建,而無需再做內(nèi)部解析))。
*
*這里的延遲創(chuàng)建是利用了函數(shù)創(chuàng)建對(duì)象的函數(shù)指針,將子類通過模版參數(shù)傳入
*/
#pragma once
#pragma warning (disable:4786)
/********************************************************************
created: 2013-1-29
author: mark
filename: AbstractFactory.h
purpose: a generic factory method lib
Copyright (C) 2008 - All Rights Reserved
*********************************************************************/
#include <string>
#include <map>
namespace lib
{
//通用工廠類,根據(jù)傳入的id創(chuàng)建產(chǎn)品對(duì)象
template <typename BaseType, typename KeyType=std::string>
class factory
{
private:
typedef std::auto_ptr<BaseType> (*BaseCreateFunc)();
typedef typename std::map<KeyType, BaseCreateFunc> FuncRegistry;
public:
static factory<BaseType, KeyType>& get_instance(){ //static singleton,不適用于多線程
static factory<BaseType, KeyType> obj;
return obj;
}
std::auto_ptr<BaseType> create(const KeyType& id) const{
std::auto_ptr<BaseType> obj;
//這句話真?zhèn)X筋,還是用C++11的auto關(guān)鍵字吧。
typename FuncRegistry::const_iterator regEntry = _registry.find(id);
//auto regEntry = _registry.find(id);
if (regEntry != _registry.end()) {
obj = regEntry->second();
}
return obj;
}
void _register_create_function(const KeyType& id, BaseCreateFunc func){_registry[id] = func;}
private:
factory(void){}
factory(const factory& other);
factory operator=(const factory& other);
private:
FuncRegistry _registry;
};
//類型(DerivedType)注冊(cè)類,只要在DerivedType類定義(DerivedType.cpp文件)的最后聲明一個(gè) lib::factory_register<Base, Derived> reg(id);對(duì)象即可
template <typename BaseType, typename DerivedType, typename KeyType=std::string>
class factory_register
{
public:
factory_register(const KeyType& id){
factory<BaseType, KeyType>::get_instance()._register_create_function(id, _create_instance);
}
private:
static std::auto_ptr<BaseType> _create_instance(){return std::auto_ptr<BaseType>(new DerivedType);}
private:
friend class factory<BaseType, KeyType>;
};
}
測(cè)試用例:
#include <iostream>
#include "AbstractFactory.h"
//基類
class Base
{
public:
virtual void print(void){
std::cout<<"base class"<<std::endl;
}
};
lib::factory_register<Base, Base> reg1("base"); //注冊(cè)Base類型,定義一個(gè)file scope的變量,通常應(yīng)該置于Base.cpp文件結(jié)尾
//派生類
class Derived:public Base
{
public:
virtual void print(void){
std::cout<<"derived class"<<std::endl;
}
};
lib::factory_register<Base, Derived> reg2("derived"); //注冊(cè)Derived類型,定義一個(gè)file scope的變量,通常應(yīng)該置于Derived.cpp文件結(jié)尾
//聲明一個(gè)全局函數(shù)(簡(jiǎn)化操作,非必需)
lib::factory<Base>& glb_GetFactory(void)
{
return lib::factory<Base>::get_instance();
}
int main(int argc, char* argv[])
{
std::auto_ptr<Base> base=glb_GetFactory().create("base");
if (base.get()){
base->print();
}
std::auto_ptr<Base> derived=glb_GetFactory().create("derived");
if (derived.get()){
derived->print();
}
system("pause");
return 0;
}