当前位置: 首页 > news >正文

C++ 简单工厂模式详解

        简单工厂模式(Simple Factory Pattern)是最简单的工厂模式,它不属于GoF 23种设计模式,但它是工厂方法模式和抽象工厂模式的基础。

概念解析

简单工厂模式的核心思想是:

  1. 将对象的创建逻辑集中在一个工厂类中

  2. 客户端不需要知道具体产品的类名,只需要知道产品对应的参数

  3. 通过传入不同的参数来创建不同的产品对象

主要组成部分

  1. 工厂类(Factory):负责创建具体产品的类,包含创建产品的静态或非静态方法

  2. 抽象产品(Product):定义产品的接口

  3. 具体产品(Concrete Product):实现抽象产品接口的具体类

代码示例

下面是一个完整的简单工厂模式示例,包含详细注释:

#include <iostream>
#include <memory>
#include <string>// 抽象产品类:形状
class Shape {
public:virtual void draw() = 0;virtual ~Shape() = default;
};// 具体产品类:圆形
class Circle : public Shape {
public:void draw() override {std::cout << "绘制圆形 ○" << std::endl;}
};// 具体产品类:矩形
class Rectangle : public Shape {
public:void draw() override {std::cout << "绘制矩形 ▭" << std::endl;}
};// 具体产品类:三角形
class Triangle : public Shape {
public:void draw() override {std::cout << "绘制三角形 △" << std::endl;}
};// 形状工厂类
class ShapeFactory {
public:// 创建形状的静态方法static std::unique_ptr<Shape> createShape(const std::string& shapeType) {if (shapeType == "Circle") {return std::make_unique<Circle>();} else if (shapeType == "Rectangle") {return std::make_unique<Rectangle>();} else if (shapeType == "Triangle") {return std::make_unique<Triangle>();} else {throw std::invalid_argument("未知的形状类型: " + shapeType);}}// 非静态创建方法std::unique_ptr<Shape> createShapeNonStatic(const std::string& shapeType) {return createShape(shapeType); // 重用静态方法的实现}
};// 客户端代码
int main() {std::cout << "=== 简单工厂模式演示 ===" << std::endl;try {// 使用静态工厂方法std::cout << "\n使用静态工厂方法:" << std::endl;auto circle = ShapeFactory::createShape("Circle");auto rectangle = ShapeFactory::createShape("Rectangle");auto triangle = ShapeFactory::createShape("Triangle");circle->draw();rectangle->draw();triangle->draw();// 使用非静态工厂方法std::cout << "\n使用非静态工厂方法:" << std::endl;ShapeFactory factory;auto circle2 = factory.createShapeNonStatic("Circle");auto rectangle2 = factory.createShapeNonStatic("Rectangle");auto triangle2 = factory.createShapeNonStatic("Triangle");circle2->draw();rectangle2->draw();triangle2->draw();// 测试未知类型std::cout << "\n测试未知类型:" << std::endl;auto unknown = ShapeFactory::createShape("Unknown"); // 这将抛出异常} catch (const std::exception& e) {std::cerr << "错误: " << e.what() << std::endl;}return 0;
}

模式优势

  1. 封装创建逻辑:将对象的创建过程集中管理,客户端无需关心创建细节

  2. 解耦:客户端代码与具体产品类解耦,只依赖抽象产品接口

  3. 简化客户端:客户端只需要知道产品对应的参数,不需要知道具体类名

  4. 易于扩展:添加新产品时只需要修改工厂类,不需要修改客户端代码

适用场景

  1. 当需要创建的对象较少且不会频繁变化时

  2. 当客户端不需要知道具体产品类名,只需要知道类型参数时

  3. 当需要集中管理对象的创建逻辑时

  4. 作为更复杂工厂模式(工厂方法、抽象工厂)的基础

    实现变体

    1. 使用枚举代替字符串

    enum class ShapeType { Circle, Rectangle, Triangle };class ShapeFactory {
    public:static std::unique_ptr<Shape> createShape(ShapeType type) {switch (type) {case ShapeType::Circle: return std::make_unique<Circle>();case ShapeType::Rectangle: return std::make_unique<Rectangle>();case ShapeType::Triangle: return std::make_unique<Triangle>();default: throw std::invalid_argument("未知的形状类型");}}
    };

    2. 使用模板工厂

    template <typename T>
    class GenericFactory {
    public:static std::unique_ptr<T> create() {return std::make_unique<T>();}
    };// 使用方式
    auto circle = GenericFactory<Circle>::create();

    3. 使用注册机制的可扩展工厂

    class ShapeFactory {
    private:using Creator = std::function<std::unique_ptr<Shape>()>;static std::map<std::string, Creator> creators;public:static void registerShape(const std::string& name, Creator creator) {creators[name] = creator;}static std::unique_ptr<Shape> createShape(const std::string& name) {auto it = creators.find(name);if (it != creators.end()) {return it->second();}throw std::invalid_argument("未知的形状类型: " + name);}
    };// 初始化静态成员
    std::map<std::string, ShapeFactory::Creator> ShapeFactory::creators = {{"Circle", []() { return std::make_unique<Circle>(); }},{"Rectangle", []() { return std::make_unique<Rectangle>(); }},{"Triangle", []() { return std::make_unique<Triangle>(); }}
    };// 可以动态注册新类型
    ShapeFactory::registerShape("Hexagon", []() { return std::make_unique<Hexagon>(); });

            

与工厂方法模式的区别

  1. 简单工厂

    • 一个工厂类负责创建所有产品

    • 通过参数判断创建哪种产品

    • 不符合开闭原则(添加新产品需要修改工厂类)

  2. 工厂方法

    • 为每种产品提供一个工厂类

    • 通过多态创建产品

    • 符合开闭原则(添加新产品只需添加新工厂类)

相关文章:

  • 游戏开发的TypeScript(3)匿名函数的常见和不常见用法
  • 基于 vue-flow 实现可视化流程图
  • Java学习手册:关系型数据库基础
  • C++ 中 virtual 的作用
  • 什么是函数重载?
  • 【开源免费】二维码批量识别-未来之窗——C#-仙盟创梦IDE
  • 在 Ubuntu 上安装 cPanel
  • 20:深度学习-多层感知器原理
  • Linxu基本操作
  • 计算机系统结构 第二章 :缓存优化
  • Java中深拷贝与浅拷贝的深入探讨
  • C++抽象基类三重防线:纯虚函数与保护构造的深度实践
  • springAop代理责任链模式源码解析
  • 《解锁GCC版本升级:开启编程新世界大门》
  • Python蓝桥杯真题代码
  • 工作记录 2015-06-01
  • 数据库介绍以及windows下mysql安装
  • vector和string的迭代器
  • BG开发者日志505:项目总体情况
  • PowerPC架构详解:定义、应用及特点
  • 《开始推理吧3》:演员没包袱,推理更共情
  • 人民日报:创新成势、澎湃向前,中国科技创新突围的密码与担当
  • 426.8万人次!长三角铁路创单日客发量历史新高
  • 王毅谈金砖国家开展斡旋调解的经验和独特优势
  • 民生访谈|支持外贸企业拓内销,上海正抓紧制定便利措施
  • 五一去哪儿| 追着花期去旅行,“赏花经济”绽放文旅新活力