没有办法,我弄不明白为什么我编辑得好好的文章贴出去都变味了。给大家带来不便不能全怪我。但是故事还没讲完,无论如何我都得讲下去。我在用英文写的那个版本里(纯粹为了看看贴出去的效果)提到使用GProductCreator至少有两个原因,其中一个就是为了用于Factory模式。另外一个原因是,一个继承体系最好不要让用户自己来构造,而是将自己托管给一个对象生成器,所以它们应当把自己所有的constructor声明为private,而将这个生成器声明为自己的friend。GProductCreator正好可以充当这个角色。当然,GProductCreator的CreatePolicy参数应当由继承体系提供。
下面的代码用于对上述方法的测试:
#include "stdafx.h"
#include
#include
#include
#include "Factory.h"
#include "Singleton.h"
using namespace std;
using namespace Loki;
//classes for testing.begin:
class GObject
{
public:
virtual void print() = 0;
};
class GTank:public GObject
{
public:
virtual void print(){cout<<"GTank/n";}
};
class GBullet:public GObject
{
public:
virtual void print(){cout<<"GBullet/n";}
};
class GETank:public GTank
{
public:
virtual void print(){cout<<"GETank/n";}
};
//classes for testing.end.
typedef unsigned long identifier_type;
template
struct GAbstractCreator
{
virtual AbstractProduct* operator()(){return 0;}
};
template
<
class Product,
class AbstructProduct = GObject,
class CreatePolicy = CreateUsingNew
>
struct GProductCreator: public GAbstractCreator
{
Product* pP;
AbstructProduct* operator()(){ return CreatePolicy::Create(pP);}
};
//Because The Create Poily I Used Is Polymorphic, Which The Loki Factory Did Not
//Suport, I Add The FactoryUsingPointer Template Class Into The Libary
typedef Loki::FactoryUsingPointer >
Factory1;
class Test;
typedef Loki::FactoryUsingPointer
Factory2;
typedef Factory1 /*Or Factory2*/ TheFactory;
typedef Loki::SingletonHolder theFactory;
//Factory Uses Like This:
//if( !theFactory::Instance().Register(GEnemyTankA::get_id(), GProductCreator()) )
// throw();
void f()
{
//Creator Test:
//the simplest using:
typedef GProductCreator TheTankCreator;
TheTankCreator theTankCreator;
theTankCreator.operator ()() ->print();
//let's use it a little more complex:
GProductCreator()()->print();
//using default template argument:
GProductCreator()()->print();
//ok, the complier seems not so displeasing, it works really well,
//I think should not curse ms this morning.
//Factory Test:
//now, let's try the Factory method:
Factory1 factory1;
factory1.Register(1, &theTankCreator);
//ok.
//Singleton Test:
//try Singleton:
theFactory::Instance().Register(2, &theTankCreator);
theFactory::Instance().CreateObject(2)->print();
//ok.
//Final Test
//now, let me give the compiler a puzzle:
SingletonHolder
<
FactoryUsingPointer<
GObject, unsigned long,
GAbstractCreator
>//FactoryUsingPointer As The First Template Argument Of SingletonHolder.
,CreateUsingMalloc
,PhoenixSingleton
>::Instance().Register(1, &GProductCreator());
//oh! not give the compiler a puzzle, but you and me!
//ok,the Creation Policy, the Factory Policy with Polymorphic Creator and
//the Singleton Pattern, they do work together very well, that's GREAT!
//ESPECIALLY, the FactoryUsingPointer and the GProductCreator are EXCITING!
}
int main(int argc, char* argv[])
{
try
{
f();
}
catch(DefaultFactoryError::Exception e)
{
cout<