c++最常用的几种设计模式

在 C++ 里,最"接地气"、面试问得最多、代码里真正天天能见到的,其实集中在下面 6 种。掌握它们就能覆盖 80% 的日常设计场景。

模式 一句话场景 C++ 惯用法要点 最常用变种
1. Singleton "全局只有一个"------日志、配置、显卡设备 1) 私构造+私赋值+公静态 Instance() 2) Meyers' Singleton(static 局部变量)线程安全又简洁 双检锁 DCLP(C++11 之后基本被 Meyers 取代)
2. Factory Method / Abstract Factory "new 太痛苦,对象类型运行时才知道"------UI 控件、数据库驱动 1) 基类提供 CreateXxx() 虚函数,返回 unique_ptr<Base> Simple Factory(一个静态 Create)
3. Observer "一对多松耦合通知"------MVC、事件总线、消息队列 1) 基类 IObserver 带纯虚 notify() 2) 用 vector<weak_ptr<IObserver> Signal/Slot(Qt、boost::signals2)
4. Strategy "算法一族随便换"------排序、压缩、支付渠道 1) 把算法封装成继承自 Strategy 的子类 2) 上下文存 unique_ptr<Strategy> Policy-based design(模板+编译期多态)
5. RAII / Wrapper(语言级模式) "资源释放一定走析构"------内存、锁、句柄 1) 构造里获取,析构里释放 2) 禁用拷贝或采用移动语义 unique_ptr/shared_ptr、lock_guard、fstream
6. Pimpl(编译防火墙) "头文件不动,实现随便改"------库开发 1) 类内只留 struct Impl; std::unique_ptr<Impl> pImpl;

1. Singleton( Meyers 版 )

cpp 复制代码
class Config {
public:
    static Config& instance() {
        static Config cfg;        // C++11 保证线程安全
        return cfg;
    }
    Config(const Config&) = delete;
    Config& operator=(const Config&) = delete;
private:
    Config() = default;
};

用法:Config::instance().get("timeout");

2. Factory 示例

cpp 复制代码
class Shape { public: virtual void draw() = 0; };
class Circle : public Shape { void draw() override {} };

using ShapePtr = std::unique_ptr<Shape>;
using Factory  = std::function<ShapePtr()>;

inline ShapePtr make_circle() { return std::make_unique<Circle>(); }

static std::unordered_map<std::string, Factory> g_reg = {
    {"circle", make_circle}
};

ShapePtr shape_factory(const std::string& key){
    return g_reg.at(key)();
}

调用:auto p = shape_factory("circle");

3. Observer 示例(weak_ptr 防悬空)

cpp 复制代码
class IObserver { public: virtual void onEvent() = 0; };

class Subject {
    std::vector<std::weak_ptr<IObserver>> subs;
public:
    void subscribe(std::shared_ptr<IObserver> o){
        subs.emplace_back(o);
    }
    void notify(){
        for (auto it = subs.begin(); it != subs.end(); ) {
            if (auto s = it->lock()) { s->onEvent(); ++it; }
            else                     { it = subs.erase(it); }
        }
    }
};

4. Strategy 示例

cpp 复制代码
class PayStrategy { public: virtual void pay(int cents) = 0; };
class AliPay : public PayStrategy { void pay(int) override {} };
class WechatPay : public PayStrategy { void pay(int) override {} };

class Order {
    std::unique_ptr<PayStrategy> strategy;
public:
    void set_pay(std::unique_ptr<PayStrategy> s){ strategy = std::move(s); }
    void checkout(int cents){ strategy->pay(cents); }
};

5. RAII / Wrapper

cpp 复制代码
std::unique_ptr<FILE, decltype(&fclose)>
make_file(const char* name){
    return {std::fopen(name,"w"), &fclose};
}

6. Pimpl

cpp 复制代码
// ====== Foo.h ======
class Foo {
public:
    Foo();
    ~Foo();
    void work();
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};

// ====== Foo.cpp ======
struct Foo::Impl {
    void workImpl() { /* 真正实现 */ }
};
Foo::Foo() : pImpl(std::make_unique<Impl>()) {}
Foo::~Foo() = default;          // 必须在 cpp 里,因为 Impl 完整类型在此处才可见
void Foo::work() { pImpl->workImpl(); }
  • 单例、工厂、观察者、策略 是"最常被问"的四大行为/创建模式。
相关推荐
鱼跃鹰飞2 小时前
DDD中的防腐层
java·设计模式·架构
会员果汁3 小时前
15.设计模式-组合模式
设计模式·组合模式
YUEchn4 小时前
无处不在的Agent
设计模式·llm·agent
茶本无香7 小时前
设计模式之二—原型模式:灵活的对象克隆机制
java·设计模式·原型模式
GISer_Jing7 小时前
Nano Banana+LoveArt三大核心功能解析:重构AI设计全链路,让创意落地更高效
人工智能·设计模式·aigc
会员果汁8 小时前
14.设计模式-备忘录模式
设计模式·备忘录模式
xiaolyuh12318 小时前
Spring 框架 核心架构设计 深度详解
spring·设计模式·spring 设计模式
GISer_Jing1 天前
智能体工具使用、规划模式
人工智能·设计模式·prompt·aigc
GISer_Jing1 天前
AI Agent:学习与适应、模型上下文协议
人工智能·学习·设计模式·aigc
小马爱打代码1 天前
MyBatis设计模式:构建者、工厂、代理模式
设计模式·mybatis·代理模式