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(); }
  • 单例、工厂、观察者、策略 是"最常被问"的四大行为/创建模式。
相关推荐
天才测试猿13 小时前
WebUI自动化测试:POM设计模式全解析
自动化测试·软件测试·python·selenium·测试工具·设计模式·测试用例
Asort14 小时前
JavaScript设计模式(十三)——责任链模式:构建灵活高效的请求处理链
前端·javascript·设计模式
笨手笨脚の14 小时前
设计模式-访问者模式
设计模式·访问者模式·行为型设计模式
bkspiderx14 小时前
C++设计模式之行为型模式:模板方法模式(Template Method)
c++·设计模式·模板方法模式
o0向阳而生0o14 小时前
108、23种设计模式之模板方法模式(17/23)
设计模式·模板方法模式
canonical_entropy17 小时前
组合为什么优于继承:从工程实践到数学本质
后端·数学·设计模式
Deschen1 天前
设计模式-工厂模式
设计模式·简单工厂模式
阿无,1 天前
Java设计模式之工厂模式
java·开发语言·设计模式
Camel卡蒙1 天前
DDD架构——充血模型、领域模型
java·设计模式·架构