1、定义两种不同分配内存创建对象的策略
template<classT>
classOpNewCreator
{
public:
staticT*create()
{
std::cout<< "OpNewCreator"<< std::endl;
returnnewT;
}
protected:
~OpNewCreator(){}
};
template<classT>
classMallocCreator
{
public:
staticT*create()
{
std::cout<< "MallocCreator"<< std::endl;
void *buf =malloc(sizeof(T));
if (!buf)
return 0;
returnnew (buf)T;
}
protected:
~MallocCreator(){}
};
2、template template定义可以根据不同型别和策略生成对象Policy
template<classT,template<class>classCreationPolicy>
classWidgetManager:publicCreationPolicy<T>
{
public:
typedefCreationPolicy<T>BaseClass;
T*create()
{
T* tmp=BaseClass::create();
return tmp;
}
};
3、定义两个实际的类型
classSliderWidget
{
public:
SliderWidget()
{
std::cout<<"Slider Widget created"<<std::endl ;
}
};
classBoxWidget
{
public:
BoxWidget()
{
std::cout<<"Box Widget created"<<std::endl;
}
};
4、使用示例
typedefWidgetManager<BoxWidget,OpNewCreator>BoxWidgetManager;
typedefWidgetManager<SliderWidget,MallocCreator>SliderWidgetManager;
intmain()
{
BoxWidgetManager boxWidgetManager;
BoxWidget* boxWidet=boxWidgetManager.create();
SliderWidgetManager silderWidgetManager;
SliderWidget* silderWidet =silderWidgetManager.create();
pause();
}