【设计模式】抽象工厂模式

概念

创建型模式


类图


代码

cpp 复制代码
#include <iostream>

using namespace std;

class Button {
public:
    virtual ~Button()= default;;
    virtual string Paint() const = 0;
};

class WinButton : public Button {
public:
    string Paint() const override {
        return "WinButton Paint\n";
    }
};

class MacButton : public Button {
public:
    string Paint() const override {
        return "MacButton Paint\n";
    }
};

class Checkbox {
public:
    virtual ~Checkbox()= default;;
    virtual string Paint() const = 0;
};

class WinCheckbox : public Checkbox {
public:
    string Paint() const override {
        return "WinCheckbox Paint\n";
    }
};

class MacCheckbox : public Checkbox {
public:
    string Paint() const override {
        return "MacCheckbox Paint\n";
    }
};

class GUIFactory {
public:
    virtual ~GUIFactory()= default;;
    virtual Button *CreateButton() const = 0;
    virtual Checkbox *CreateCheckbox() const = 0;
};

class WinFactory : public GUIFactory {
public:
    Button *CreateButton() const override {
        return new WinButton();
    }

    Checkbox *CreateCheckbox() const override {
        return new WinCheckbox();
    }
};

class MacFactory : public GUIFactory {
public:
    Button *CreateButton() const override {
        return new MacButton();
    }

    Checkbox *CreateCheckbox() const override {
        return new MacCheckbox();
    }
};

class Application {
public:
    explicit Application(GUIFactory* factory) {
        this->factory = factory;
    }

    void CreateUI() {
        button = factory->CreateButton();
        checkbox = factory->CreateCheckbox();
    }

    void Paint() {
        cout << button->Paint();
        cout << checkbox->Paint();
    }

private:
    GUIFactory* factory{};
    Button* button{};
    Checkbox *checkbox{};
};

int main(int argc, char *argv[]) {
    string config = "Windows";
    GUIFactory *factory;

    if (config == "Windows") {
        factory = new WinFactory();
    } else if (config == "Mac") {
        factory = new MacFactory();
    } else {
        cout << "Error! Unknown Operating System Type!" << endl;
        return -1;
    }

    Application app = Application(factory);
    app.CreateUI();
    app.Paint();

    delete factory;

    return 0;
}
相关推荐
亦暖筑序1 天前
Java 8老系统Browser Agent实战:三层拦截把AI操作后台变成可审计流程
java·后端·设计模式
用户805533698031 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK2 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境2 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境2 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴3 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
青禾网络3 天前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO4 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯4 天前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术5 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播