Just enjoy programming

c++设计模式(九) 抽象工厂(Abstract Factory)

      抽象工厂(Abstract Factory)模式看起来和前面看到的工厂方法很相似,只是它使用若干工厂方法(Factory Method)模式。每个工厂方法模式创建一个不同类型的对象。当创建一个工厂对象时,要决定将如何使用由那个工厂创建的所有对象。示例代码如下(假设要创建一个通用的游戏环境,并且希望它能支持不同类型的游戏):
#include<iostream>
using namespace std;

class Obstacle
{
public:
    virtual void action()=0;
};

class Player
{
public:
    virtual void interactWith(Obstacle*)=0;
};

class Kitty: public Player
{
    virtual void interactWith(Obstacle *ob)
    {
        cout<<"Kitty has encountered a";
        ob->action();
    }
};

class KungFuGuy: public Player
{
    virtual void interactWith(Obstacle* ob)
    {
        cout<<"KungFuGuy now battles against a";
        ob->action();
    }
};
class Puzzle: public Obstacle
{
public:
    void action(){cout<<"Puzzle"<<endl;}
};

class NastyWeapon: public Obstacle
{
public:
    void action(){cout<<"NastyWeapon"<<endl;}
};

//the abstract factory
class GameElementFactory
{
public:
    virtual Player* makePlayer()=0;
    virtual Obstacle* makeObstacle()=0;
};

//concreate factories
class KittiesAndPuzzles:public GameElementFactory
{
public:
    virtual Player* makePlayer(){return new Kitty;}
    virtual Obstacle * makeObstacle(){return new Puzzle;}
};

class KillAndDismember:public GameElementFactory
{
public:
    virtual Player* makePlayer(){return new KungFuGuy;}
    virtual Obstacle *makeObstacle(){return new NastyWeapon;}
};


class GameEnvironment
{
    GameElementFactory* gef;
    Player* p;
    Obstacle *ob;
public:
    GameEnvironment(GameElementFactory * factory)
        :gef(factory),p(factory->makePlayer()),ob(factory->makeObstacle()){}
    void play(){p->interactWith(ob);}
    ~GameEnvironment()
    {
        delete p;
        delete ob;
        delete gef;
    }
};

int main()
{
    GameEnvironment
        g1(new KittiesAndPuzzles),
        g2(new KillAndDismember);
    g1.play();
    g2.play();
}

在此环境中,Player对象与Obstacle 对象交互,但是Player和Obstacle类型依赖于具体的游戏。可以选择特定的GameElementFactory来决定游戏的类型,然后GameEnvironment控制游戏的设置和进行。在本例中,游戏的设置和进行很简单,但是那些动作在很大程度上决定了游戏的结果。

posted on 2011-05-03 23:40 周强 阅读(362) 评论(0)  编辑 收藏 引用 所属分类: c/c++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理