0
点赞
收藏
分享

微信扫一扫

【设计模式笔记】C++抽象工厂模式


围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。

提供了一种创建对象的最佳方式。

抽象工厂模式是一种设计模式,它提供了一个接口来创建一系列相关或依赖对象,而无需指定它们具体的类。这种模式的目的是使用抽象类来定义和维护对象之间的关系,以便在不直接实例化类的情况下创建一组对象。

在一个工厂里聚合多个同类产品

优点:当一个产品族的多个对象被设计成一起工作时,它能保证客户端始终只使用同一个产品族中的对象

缺点:产品族拓展非常困难,要增加一个系列的某一产品,既要在抽象的Creator里加代码,又要在具体的里面加代码

#include <iostream>
using namespace std;

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

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

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

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

class Puzzle : public Obstacle {
public:
    void action() override { cout << "Puzzle\n"; }
};

class NastyWeapon : public Obstacle {
public:
    void action() override { cout << "NastyWeapon\n"; }
};

// 抽象工厂
class GameElementFactory {
public:
    virtual Player* makePlayer() = 0;
    virtual Obstacle* makeObstacle() = 0;
};

// 具体工厂实现
class KittiesAndPuzzles : public GameElementFactory {
public:
    Player* makePlayer() override {
        return new Kitty;
    }
    Obstacle* makeObstacle() override {
        return new Puzzle;
    }
};

class KillAndDismember : public GameElementFactory {
public:
    Player* makePlayer() override {
        return new KungFuGuy;
    }
    Obstacle* makeObstacle() override {
        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;
        // 注意:这里不删除工厂gef,因为工厂通常由调用者管理
    }
};

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

举报

相关推荐

0 条评论