接着上一章的单例工厂模式来继续思考:
如果在新增金抢菜器时,新增的工厂类型可以不用增加class的数量就好了。最直接的想法就是使用map结构,把工厂类抽象为一个函数,然后map结构中的first存type,second存lambda函数。为了方便存储到map结构中,现在介绍一种使用工厂管理类的方法,用户把新增的产品注册到工厂管理类里,在需要new产品的时候,去工厂管理类遍历寻找该成员。
但是前提是这个类名可以直接被new出来,并且构造函数没有参数传入。
产品基类
class IGrep
{
virtual void doAction()=0;
}
产品
class GoldGrep:public IGrep
{
doAction(){cout<<"Gold"}
}
工厂基类
class IFactor
{
virtual IGrep* Create()=0;
}
class FactorManager
{
static FactorManager* getInstance();
addFactor(string type)
chooseFactor2Creat(string type);
map<string,function<Ibject*()>> m_createFun()//use lambda Function
}
FactorManager* FactorManager::getInstance()
{
static FactorManager instance;
return &instance;
}
FactorManager::addFactor(string type)
{
auto it = map<string,function<IObejct*<>>::iterator
if(m_creatFun.end() != m_creatFun.find(type))
{
m_creatFun.insert({type,[]{return new string2indetifier(type)}})//把string变成系统标识符,就相当于直接new 一个class
}
}
FactorManager::chooseFactor2Creat(string type)
{
map<string,function<IObecjt*<>>::iterator it = m_creatFun.find(type)
if (m_creatFun.end() != it)
{
return it->second
}
}
int main()
{
string objectType = "GoldGrep" ;
FactorManager::getInstance()->addFactor(objectType);
function<IObject*<>> creatFun = FactorManager::getInstance()->chooseFactor2Creat(objectType);
IGrep *object = creatFunc();
}