4

Loki 库为构建 AbstractFactory 模式提供了预定义的接口。特别是,我对基于原型的抽象工厂感兴趣。

假设我们有一个具有抽象实体的游戏应用程序:

class Soldier{ };
class Monster{ };
class SuperMonster{ };

和具体实体:

class EasySoldire : public Soldier{ };

class EasyMoster : public Monster{ };

class EasySuperMonster : public SuperMonster{ };

等等MediumHard

现在我想创建基于原型的简易级别工厂。

下面是它在 Loki 中的实现方式(Alexandrescu 的现代 C++ 设计):

template
<
    class AbstractFact,
    template <class, class> class Creator,
    class TList = typename AbstractFact::ProductList
>
class ConcreteFactory;

template <class ConcreteProduct, class Base>
class PrototypeFactoryUnit : public Base
{
    typedef typename Base::ProductList BaseProductList;
protected;
    typedef typename Base::ProductList TailProductList;
public;
    typedef typename Base::ProductList::Head AbstractProduct;
    PrototypeFactoryUnit(AbstractProduct* p = 0)
   :pPrototype_(p) {}
    friend void DoGetPrototype(const PrototypeFactoryUnit& me,
                                AbstractProduct*& pPrototype)
    {
        pPrototype = me.pPrototype_;
    }

    friend void DoSetPrototype(PrototypeFactoryUnit& me,
                               AbstractProduct* pObj)
    {
        me.pPrototype_=pObj;
    }

    template <class U>
    void GetPrototype(AbstractProduct*& p)
    {
        return DoGetPrototype(*this, p);
    }

    template <class U>
    void SetPrototype(U* pObj)
    {
        DoSetPrototype(*this, pObj);
    }

    AbstractProduct* DoCreate(Type2Type<AbstractProduct>)
    {

       assert(pPrototype_);
       return pPrototype_->Clone();
    }
    private:
    AbstractProduct* pPrototype_;
};

所以 ConcreteFactory 看起来像:

typedef AbstractFactory
<
     TYPELIST_3(Soldier, Monster, SuperMonster)
>
AbstractEnemyFactory;

typedef ConcreteFactory
<
    AbstractEnemyFactory,
    PrototypeFactoryUnit
>
EnemyFactory;

现在我的问题是我们如何Easy从那个具体工厂定义关卡工厂?

4

0 回答 0