C++设计模式简介
设计模式(design patterns)是经过时间验证的架构解决方案,用于解决典型的开发任务。在C++世界中,它们尤为重要,因为它们能够创建灵活、可扩展且易于维护的代码。在本文中,我们将分析四种基本模式:Singleton、Factory Method、Observer和Strategy,并提供现代C++(C++17/20)的完整示例。
每种模式都将附带实际示例、类图和应用说明。本材料面向已经熟悉C++和OOP基础的开发者。
1. 创建型模式 Singleton(单例)
Singleton确保一个类只有一个实例,并提供一个全局访问点。在C++中,经典实现使用静态方法和私有构造函数。
何时使用
- 管理数据库连接
- 日志系统
- 缓存管理器
- 应用程序配置
实现示例(线程安全的Singleton)
#include <iostream>#include <mutex>#include <memory>
class Logger {private: static std::unique_ptr<Logger> instance; static std::mutex mtx; Logger() { std::cout << "Logger создан" << std::endl; } public: Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; static Logger* getInstance() { std::lock_guard<std::mutex> lock(mtx); if (!instance) { instance.reset(new Logger()); } return instance.get(); } void log(const std::string& msg) { std::cout << "[LOG] " << msg << std::endl; }};
std::unique_ptr<Logger> Logger::instance = nullptr;std::mutex Logger::mtx;
int main() { Logger* log1 = Logger::getInstance(); Logger* log2 = Logger::getInstance(); log1->log("Тестовое сообщение"); // log1和log2指向同一个对象 std::cout << "log1 == log2: " << (log1 == log2) << std::endl; return 0;}现代C++方法(Meyers' Singleton)
class ConfigManager {public: static ConfigManager& getInstance() { static ConfigManager instance; // C++11+中线程安全 return instance; } void setParam(const std::string& key, const std::string& value) { params[key] = value; } std::string getParam(const std::string& key) { return params[key]; } private: ConfigManager() = default; std::map<std::string, std::string> params;};2. 创建型模式 Factory Method(工厂方法)
Factory Method定义了一个创建对象的接口,但允许子类选择要创建的具体类。当对象类型事先未知时,此模式特别有用。
模式结构
- Product — 抽象产品类
- ConcreteProduct — 具体产品实现
- Creator — 带有工厂方法的抽象创建者类
- ConcreteCreator — 重写工厂方法
示例:通知系统
#include <iostream>#include <memory>#include <string>
// 抽象产品class Notification {public: virtual void send(const std::string& message) = 0; virtual ~Notification() = default;};
// 具体产品class EmailNotification : public Notification {public: void send(const std::str