template policy模式实现
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
template <class T>
struct OpNewCreator
{
static T *Create()
{
return new T;
}
};
template <class T>
struct MallocCreator
{
static T *Create()
{
void *buf = std::malloc(sizeof(T));
if (!buf) return 0;
return new(buf) T;
}
};
template <class T>
struct PrototypeCreator
{
PrototypeCreator(T *pObj = 0)
: pPrototype_(pObj)
{ }
T *Create()
{
return pPrototype_ ? pPrototype_->Clone() : 0;
}
T *GetPrototype()
{
return pPrototype_;
}
void SetPrototype(T *pObj)
{
pPrototype_ = pObj;
}
private:
T *pPrototype_;
};
class Widget
{
};
class Gadget
{
};
template <template <class Created> class CreationPolicy>
class WidgetMannager : public CreationPolicy<Widget>
{
public:
void Print() { cout << "Widtget Manager" << endl; }
void DoSomething()
{
Gadget *pObj = CreationPolicy<Gadget>().Create();
}
};
int main()
{
typedef WidgetMannager<OpNewCreator> MyWidgetMgr;
MyWidgetMgr mgr;
mgr.Print();
return 0;
}