范型抽象工厂模式
本节介绍范型编程中的抽象工厂模式。
一、AbstractFactory的定义
template< class TList, template class Unit = AbstractFactoryUnit>
class AbstractFactory : public GenScatterHierarchy{
public:
typedef TList ProductList;
template T* Create() {
Unit & unit = *this;
return unit.DoCreate(Type2Type());
}
};
其中的Type2Type定义如下
template
struct Type2Type{
typedef T OriginalType;
};
其中的AbstractFactoryUnit定义如下
template class AbstractFactoryUnit
{
public:
virtual T* DoCreate(Type2Type) = 0;
virtual ~AbstractFactoryUnit() {}
};
其中GenScatterHierarchy的定义如下
template class Unit> class GenScatterHierarchy;
// GenScatterHierarchy specialization: Typelist to Unit
template class Unit>
class GenScatterHierarchy, Unit> : public GenScatterHierarchy , public GenScatterHierarchy{
public:
typedef typename Typelist TList;
typedef typename GenScatterHierarchy LeftBase;
typedef typename GenScatterHierarchy RightBase;
};
// Pass an atomic type (non-typelist) to Unit
template class Unit>
class GenScatterHierarchy : public Unit{
typedef typename Unit LeftBase;
};
// Do nothing for NullType
template class Unit>
class GenScatterHierarchy{
};
其中Typelist定义如下
template
struct Typelist{
typedef T Head;
typedef U Tail;
};
#define TYPELIST_1(T1) Typelist
#define TYPELIST_2(T1, T2) Typelist
#define TYPELIST_3(T1, T2, T3) Typelist
#define TYPELIST_4(T1, T2, T3, T4) \
Typelist.
..
#define TYPELIST_50(...) ...
二、AbstractFactory的实现
使用ConcreteFactory去具体实现一个抽象工厂
ConcreteFactory的定义如下
template< class AbstractFact, template class Creator = OpNewFactoryUnit, class TList>
class ConcreteFactory : public GenLinearHierarchy< typename TL::Reverse::Result, Creator, AbstractFact>{
public:
typedef typename AbstractFact::ProductList ProductList;
typedef TList ConcreteProductList;
};
其中OpNewFactoryUnit的定义如下
template class OpNewFactoryUnit : public Base{
typedef typename Base::ProductList BaseProductList;
protected:
typedef typename BaseProductList::Tail ProductList;
public:
typedef typename BaseProductList::Head AbstractProduct;
ConcreteProduct* DoCreate(Type2Type) {
return new ConcreteProduct;
}
};
其中GenLinearHierarchy的定义如下
template< class TList, template class Unit, class Root = EmptyType>
class GenLinearHierarchy;
template< class T1, class T2, template class Unit, class Root>
class GenLinearHierarchy, Unit, Root> : public Unit< T1, GenLinearHierarchy >{
};
template< class T, template class Unit, class Root>
class GenLinearHierarchy : public Unit{
};
TL::Reverse
三、实际使用
实际使用时,代码如下
typedef ConcreteFactory<
AbstractEnemyFactory, // the abstract factory to implement
OpNewFactoryUnit, //policy for creating objects,for example using new
TYPELIST_3(SillySoldier, SillyMonster, SillySuperMonster) //concrete classes factory creates
>EasyLevelEnemyFactory;
// Application code
typedef AbstractFactory AbstractEnemyFactory;
AbstractEnemyFactory* p = new EasyLevelEnemyFactory;
Monster* pOgre=p->Create();
其中AbstractFactory经由TYPELIST_3(Soldier, Monster, SuperMonster)生成的继承体系如下
参考资料
- <
> Andrei Alexandrescu