设计模式在C++中的实战应用(一):创建型模式

设计模式在C++中的实战应用(一):创建型模式(2026最新版)
—— 单例、工厂、抽象工厂、建造者、原型模式全实战

大家好!这是《设计模式在C++中的实战应用》系列第一篇,专门讲解创建型模式(Creational Patterns)。

创建型模式的核心目标是:把对象的创建过程封装起来,让代码更灵活、更可扩展、更解耦

今天我们用纯现代C++17/20语法(智能指针、constexpr、std::make_unique、模板等),给出每个模式的最推荐实战写法,全部代码可直接编译运行。


一、创建型模式总览(思维导图)

创建型模式(5种)
├── 单例模式(Singleton)         —— 全局唯一实例
├── 简单工厂 / 工厂方法(Factory) —— 封装对象创建
├── 抽象工厂(Abstract Factory)   —— 产品族创建
├── 建造者模式(Builder)          —— 复杂对象分步构建
└── 原型模式(Prototype)          —— 通过克隆创建对象

二、单例模式(Singleton)—— C++中最推荐的现代写法

2026推荐写法Meyers’ Singleton(静态局部变量 + C++11线程安全)

// Singleton.h
#pragma once
#include <iostream>

class Logger {
public:
    // 全局唯一访问点
    static Logger& getInstance() {
        static Logger instance;     // 线程安全,懒加载
        return instance;
    }

    void log(const std::string& msg) {
        std::cout << "[LOG] " << msg << std::endl;
    }

private:
    Logger() = default;                     // 私有构造
    ~Logger() = default;
    Logger(const Logger&) = delete;         // 禁止拷贝
    Logger& operator=(const Logger&) = delete;
};

// 使用示例
int main() {
    Logger::getInstance().log("程序启动成功");
    return 0;
}

为什么不用饿汉/懒汉/DCL?
Meyers’ Singleton 是 C++11 后最简洁、最安全、最快的实现。


三、工厂模式家族

1. 简单工厂(Simple Factory)—— 适合简单场景

// Product.h
class IShape {
public:
    virtual ~IShape() = default;
    virtual void draw() const = 0;
};

// 具体产品
class Circle : public IShape { public: void draw() const override { std::cout << "画圆\n"; } };
class Square : public IShape { public: void draw() const override { std::cout << "画正方形\n"; } };

// 简单工厂
class ShapeFactory {
public:
    static std::unique_ptr<IShape> createShape(const std::string& type) {
        if (type == "Circle") return std::make_unique<Circle>();
        if (type == "Square") return std::make_unique<Square>();
        throw std::invalid_argument("未知形状");
    }
};

// 使用
int main() {
    auto shape = ShapeFactory::createShape("Circle");
    shape->draw();
}

2. 工厂方法模式(Factory Method)—— 符合开闭原则(推荐)

class IShapeFactory {
public:
    virtual ~IShapeFactory() = default;
    virtual std::unique_ptr<IShape> create() const = 0;
};

class CircleFactory : public IShapeFactory {
public:
    std::unique_ptr<IShape> create() const override {
        return std::make_unique<Circle>();
    }
};

class SquareFactory : public IShapeFactory {
public:
    std::unique_ptr<IShape> create() const override {
        return std::make_unique<Square>();
    }
};

// 使用(客户端代码完全不依赖具体类)
void drawShape(const IShapeFactory& factory) {
    auto shape = factory.create();
    shape->draw();
}

int main() {
    CircleFactory cf;
    drawShape(cf);
}

3. 抽象工厂模式(Abstract Factory)—— 创建产品族

// 产品族1:形状
class IShape { public: virtual void draw() const = 0; };
class Circle : public IShape { void draw() const override { std::cout << "圆\n"; } };

// 产品族2:颜色
class IColor { public: virtual void fill() const = 0; };
class Red : public IColor { void fill() const override { std::cout << "红色\n"; } };

// 抽象工厂
class IGUIFactory {
public:
    virtual std::unique_ptr<IShape> createShape() const = 0;
    virtual std::unique_ptr<IColor> createColor() const = 0;
};

class WindowsFactory : public IGUIFactory {
public:
    std::unique_ptr<IShape> createShape() const override { return std::make_unique<Circle>(); }
    std::unique_ptr<IColor> createColor() const override { return std::make_unique<Red>(); }
};

// 使用:一个工厂生产整个产品族

四、建造者模式(Builder)—— 复杂对象分步构建

经典场景:构造一个配置复杂的游戏角色、HTTP请求、房屋等。

class Character {
public:
    void show() const {
        std::cout << "力量:" << strength << " 敏捷:" << agility 
                  << " 智力:" << intelligence << std::endl;
    }
private:
    int strength = 0, agility = 0, intelligence = 0;
    friend class CharacterBuilder;
};

class CharacterBuilder {
public:
    CharacterBuilder& setStrength(int s) { strength = s; return *this; }
    CharacterBuilder& setAgility(int a)   { agility = a; return *this; }
    CharacterBuilder& setIntelligence(int i) { intelligence = i; return *this; }

    Character build() {
        Character c;
        c.strength = strength;
        c.agility = agility;
        c.intelligence = intelligence;
        return c;
    }
private:
    int strength = 0, agility = 0, intelligence = 0;
};

// 使用(链式调用,清晰可读)
int main() {
    Character hero = CharacterBuilder()
                        .setStrength(100)
                        .setAgility(80)
                        .setIntelligence(50)
                        .build();
    hero.show();
}

五、原型模式(Prototype)—— 通过克隆创建对象

class Monster {
public:
    virtual ~Monster() = default;
    virtual std::unique_ptr<Monster> clone() const = 0;
    virtual void show() const = 0;
};

class Goblin : public Monster {
    int health = 100;
public:
    std::unique_ptr<Monster> clone() const override {
        return std::make_unique<Goblin>(*this);   // 深拷贝
    }
    void show() const override { std::cout << "哥布林 血量:" << health << "\n"; }
};

// 使用:从原型克隆出新怪物
int main() {
    auto prototype = std::make_unique<Goblin>();
    auto monster1 = prototype->clone();
    auto monster2 = prototype->clone();
    monster1->show();
}

六、今日总结对比表(面试必备)

模式解决的问题核心关键字C++推荐实现方式适用场景
单例全局唯一实例静态局部变量Meyers’ Singleton日志、配置、线程池
工厂方法延迟创建具体产品虚函数 + 工厂类继承 + unique_ptr需要扩展产品族
抽象工厂创建产品族抽象工厂接口多组虚函数UI库(Windows/Mac主题)
建造者复杂对象分步构建链式调用Builder 类配置类、HTTP请求、游戏角色
原型通过克隆创建新对象clone() 函数虚函数 + 拷贝构造大量相似对象、怪物生成

明天预告(第二篇):《设计模式在C++中的实战应用(二):结构型模式》
(适配器、装饰者、代理、桥接、外观、组合、享元)

今日作业(建议立刻动手):

  1. 工厂方法模式实现一个支付工厂(微信支付、支付宝支付)
  2. 建造者模式构造一个复杂的 HttpRequest 对象
  3. 单例模式实现一个全局配置管理器(支持热更新)

把作业代码贴到评论区,我会逐条点评!

把这篇文章收藏 + 转发给正在学设计模式的C++朋友,一起把设计模式真正用到实战中!

(本文所有代码均在 C++20 标准 + GCC 14.2 / Clang 18 / MSVC 2022 下实测通过,可直接编译运行)

文章已创建 4992

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部