C++设计模式学习与运用 从理论到实战掌握核心技巧 解决软件开发中的常见难题与挑战

引言:设计模式在现代C++开发中的核心地位
在软件开发领域,设计模式(Design Patterns)是解决常见架构问题的最佳实践总结。对于C++开发者而言,掌握设计模式不仅能提升代码质量,还能有效应对软件开发中的各种挑战。设计模式本质上是经过验证的、可复用的解决方案,它们帮助我们构建更加灵活、可维护和可扩展的系统。
C++作为一门支持多范式的编程语言,其强大的特性(如模板、RAII、多态等)为设计模式的实现提供了丰富的手段。然而,C++的复杂性也意味着我们需要更深入地理解如何正确应用这些模式,避免过度设计或误用。
本文将从理论基础出发,深入探讨几种核心设计模式,通过完整的代码示例展示其实战应用,并分析如何利用这些模式解决软件开发中的常见难题。
单例模式(Singleton Pattern)
理论基础
单例模式确保一个类只有一个实例,并提供一个全局访问点。这在需要全局状态管理(如配置管理器、日志系统)时非常有用。
C++实现挑战与最佳实践
在C++中实现单例模式需要考虑线程安全、资源释放和继承等问题。现代C++(C++11及以上)提供了更好的工具来处理这些挑战。
完整代码示例
#include
#include
#include

class Singleton {
private:
// 私有构造函数防止外部实例化
Singleton() = default;

// 删除拷贝构造和赋值操作
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;

// 静态实例(C++11起静态局部变量初始化是线程安全的)
static Singleton* instance;
static std::mutex mutex_;

public:
// 获取实例的静态方法
static Singleton& getInstance() {
// 双重检查锁定模式(Double-Checked Locking Pattern)
if (instance == nullptr) {
std::lock_guard lock(mutex_);
if (instance == nullptr) {
instance = new Singleton();
}
}
return *instance;
}

// 示例业务方法
void doSomething() {
std::cout << "Singleton is doing something!" << std::cout; } // 资源清理(可选,依赖于RAII) static void destroy() { if (instance) { delete instance; instance = nullptr; } } }; // 静态成员定义 Singleton* Singleton::instance = nullptr; std::mutex Singleton::mutex_; // 使用示例 int main() { Singleton& s1 = Singleton::getInstance(); Singleton& s2 = Singleton::getInstance(); s1.doSomething(); // 验证是否为同一实例 std::cout << "s1 address: " << &s1 << std::endl; std::cout << "s2 address: " << &s2 << std::endl; // 清理资源(在实际项目中可依赖RAII自动清理) Singleton::destroy(); return 0; } 实战应用与挑战解决 常见难题 :在多线程环境中,传统单例实现可能导致竞态条件。 解决方案 :使用C++11的静态局部变量初始化(线程安全)或双重检查锁定模式。现代C++推荐使用Meyers’ Singleton(静态局部变量版本),因为它更简洁且线程安全。 进阶考虑 :对于需要继承的单例,可以使用CRTP(奇异递归模板模式)来实现可继承的单例。 工厂模式(Factory Pattern) 理论基础 工厂模式包括简单工厂、工厂方法和抽象工厂。它通过封装对象创建逻辑,实现创建与使用的解耦,便于扩展新的产品类型。 C++实现与模板应用 C++的模板特性可以大大增强工厂模式的灵活性,实现编译时多态。 完整代码示例:抽象工厂 #include
#include
#include
#include
#include

// 产品基类
class Product {
public:
virtual ~Product() = default;
virtual void operation() const = 0;
};

// 具体产品A
class ConcreteProductA : public Product {
public:
void operation() const override {
std::cout << "ConcreteProductA operation" << std::endl; } }; // 具体产品B class ConcreteProductB : public Product { public: void operation() const override { std::cout << "ConcreteProductB operation" << std::endl; } }; // 抽象工厂 class ProductFactory { public: virtual ~ProductFactory() = default; virtual std::unique_ptr create() = 0;
};

// 具体工厂A
class ConcreteFactoryA : public ProductFactory {
public:
std::unique_ptr create() override {
return std::make_unique();
}
};

// 具体工厂B
class ConcreteFactoryB : public ProductFactory {
public:
std::unique_ptr create() override {
return std::make_unique();
}
};

// 注册式工厂(使用函数映射)
class DynamicFactory {
private:
using Creator = std::function()>;
std::unordered_map creators_;

public:
template
void registerProduct(const std::string& name) {
creators_[name] = []() -> std::unique_ptr {
return std::make_unique();
};
}

std::unique_ptr create(const std::string& name) {
auto it = creators_.find(name);
if (it != creators_.end()) {
return it->second();
}
return nullptr;
}
};

// 使用示例
int main() {
// 传统工厂方法
std::unique_ptr factoryA = std::make_unique();
std::unique_ptr productA = factoryA->create();
productA->operation();

// 动态注册工厂
DynamicFactory dynamicFactory;
dynamicFactory.registerProduct(“A”);
dynamicFactory.registerProduct(“B”);

auto product1 = dynamicFactory.create(“A”);
auto product2 = dynamicFactory.create(“B”);

if (product1) product1->operation();
if (product2) product2->operation();

return 0;
}
实战应用与挑战解决
常见难题
:当产品类型频繁变化时,硬编码的工厂难以维护。
解决方案
:使用注册式工厂模式,通过配置或注册机制动态添加产品类型,无需修改工厂代码,符合开闭原则。
观察者模式(Observer Pattern)
理论基础
观察者模式定义了对象间的一对多依赖关系,当一个对象状态改变时,所有依赖者都会收到通知并自动更新。这是事件驱动系统的核心模式。
C++实现:信号与槽机制
现代C++可以使用函数对象和lambda表达式实现轻量级的观察者模式。
完整代码示例
#include
#include
#include
#include

// 前向声明
class Observer;

// 主题(Subject)
class Subject {
private:
std::vector> observers_;
int state_ = 0;

public:
void attach(std::function observer) {
observers_.push_back(observer);
}

void detach(const std::function& observer) {
// 移除特定观察者(需要比较函数对象,实际中可能需要使用ID)
// 这里简化处理,实际中可能需要包装器
}

void setState(int state) {
state_ = state;
notify();
}

int getState() const { return state_; }

private:
void notify() {
for (const auto& observer : observers_) {
observer(state_);
}
}
};

// 观察者(Observer)
class Observer {
public:
virtual ~Observer() = default;
virtual void update(int state) = 0;
};

// 具体观察者
class ConcreteObserver : public Observer {
private:
std::string name_;
public:
ConcreteObserver(const std::string& name) : name_(name) {}

void update(int state) override {
std::cout << name_ << " received update: state = " << state << std::endl; } }; // 使用函数对象的现代实现 class EventManager { private: using Callback = std::function;
std::vector callbacks_;

public:
void subscribe(Callback callback) {
callbacks_.push_back(callback);
}

void notify(const std::string& message) {
for (const auto& callback : callbacks_) {
callback(message);
}
}
};

// 使用示例
int main() {
// 传统观察者模式
Subject subject;
auto obs1 = std::make_shared(“Observer1”);
auto obs2 = std::make_shared(“Observer2”);

subject.attach([obs1](int state) { obs1->update(state); });
subject.attach([obs2](int state) { obs2->update(state); });

subject.setState(10);
subject.setState(20);

// 现代函数对象实现
EventManager eventManager;

// 使用lambda订阅
eventManager.subscribe([](const std::string& msg) {
std::cout << "Lambda1: " << msg << std::1; }); eventManager.subscribe([](const std::string& msg) { std::cout << "Lambda2: " << msg << std::endl; }); eventManager.notify("Hello Event!"); return 0; } 实战应用与挑战解决 常见难题 :在多线程环境中,观察者通知可能导致死锁或性能瓶颈。 解决方案 :使用异步通知机制或发布-订阅模式。可以结合 std::async 或消息队列实现异步解耦,避免在通知过程中持有锁。 策略模式(Strategy Pattern) 理论基础 策略模式定义一系列算法,将每个算法封装起来,并使它们可以互换。这使得算法的变化独立于使用它的客户端。 C++实现:模板与函数对象 C++的模板和函数对象可以实现零开销的策略模式,避免运行时开销。 完整代码示例 #include
#include
#include
#include

// 策略接口
class SortStrategy {
public:
virtual ~SortStrategy() = default;
virtual void sort(std::vector& data) = 0;
};

// 快速排序策略
class QuickSort : public SortStrategy {
public:
void sort(std::vector& data) override {
std::cout << "Using QuickSort" << std::endl; // 实际排序实现(简化) std::sort(data.begin(), data.end()); } }; // 冒泡排序策略 class BubbleSort : public SortStrategy { public: void sort(std::vector& data) override {
std::cout << "Using BubbleSort" << std::endl; // 实际排序实现(简化) std::sort(data.begin(), data.end()); } }; // 策略上下文 class Context { private: std::unique_ptr strategy_;

public:
Context(std::unique_ptr strategy)
: strategy_(std::move(strategy)) {}

void setStrategy(std::unique_ptr strategy) {
strategy_ = std::move(strategy);
}

void executeStrategy(std::vector& data) {
if (strategy_) {
strategy_->sort(data);
}
}
};

// 模板实现的零开销策略模式
template
class Sorter {
private:
SortFunc sortFunc_;

public:
void sort(std::vector& data) {
sortFunc_(data);
}
};

// 函数对象策略
struct QuickSortFunc {
void operator()(std::vector& data) {
std::cout << "Template QuickSort" << std::endl; std::sort(data.begin(), data.end()); } }; struct MergeSortFunc { void operator()(std::vector& data) {
std::cout << "Template MergeSort" << std::endl; std::sort(data.begin(), data.end()); } }; // 使用示例 int main() { std::vector data = {5, 2, 8, 1, 9};

// 传统策略模式
Context context(std::make_unique());
context.executeStrategy(data);

context.setStrategy(std::make_unique());
context.executeStrategy(data);

// 模板策略模式(编译时多态,无虚函数开销)
Sorter templateSorter;
templateSorter.sort(data);

Sorter templateSorter2;
templateSorter2.sort(data);

return 0;
}
实战应用与挑战解决
常见难题
:运行时策略切换的性能开销。
解决方案
:对于性能敏感的场景,使用模板实现的策略模式(编译时多态)可以消除虚函数调用开销。对于需要运行时动态切换的场景,使用函数对象或
std::function
包装lambda表达式。
装饰器模式(Decorator Pattern)
理论基础
装饰器模式动态地给对象添加额外的职责,而不改变其结构。这是实现开闭原则的经典模式。
C++实现:RAII与组合
C++的RAII特性使得装饰器模式特别优雅,可以自动管理资源。
完整代码示例
#include
#include
#include

// 组件接口
class Component {
public:
virtual ~Component() = default;
virtual std::string operation() const = 0;
};

// 具体组件
class ConcreteComponent : public Component {
public:
std::string operation() const override {
return “ConcreteComponent”;
}
};

// 装饰器基类
class Decorator : public Component {
protected:
std::unique_ptr component_;

public:
Decorator(std::unique_ptr component)
: component_(std::move(component)) {}

std::string operation() const override {
return component_->operation();
}
};

// 具体装饰器A
class ConcreteDecoratorA : public Decorator {
public:
using Decorator::Decorator;

std::string operation() const override {
return “DecoratorA(” + Decorator::operation() + “)”;
}
};

// 具体装饰器B
class ConcreteDecoratorB : public Decorator {
public:
using Decorator::Decorator;

std::string operation() const override {
return “DecoratorB[” + Decorator::operation() + “]”;
}
};

// RAII装饰器:自动计时
class TimingDecorator : public Decorator {
public:
using Decorator::Decorator;

std::string operation() const override {
auto start = std::chrono::high_resolution_clock::now();
std::string result = Decorator::operation();
auto end = std::chrono::high_resolution_clock::now();

auto duration = std::chrono::duration_cast(end – start);
std::cout << "Operation took " << duration.count() << " microseconds" << std::endl; return result; } }; // 使用示例 int main() { // 创建基础组件 auto component = std::make_unique();

// 装饰一层
auto decorated1 = std::make_unique(std::move(component));

// 再装饰一层
auto decorated2 = std::make_unique(std::move(decorated1));

std::cout << decorated2->operation() << std::endl; // RAII装饰器示例 auto timedComponent = std::make_unique(
std::make_unique()
);
std::cout << timedComponent->operation() << std::0; return 0; } 实战应用与挑战解决 常见难题 :装饰器过多导致对象结构复杂。 解决方案 :使用工厂模式创建装饰器链,或提供流式接口(Builder模式)来简化装饰器的组合。 建造者模式(Builder Pattern) 理论基础 建造者模式将复杂对象的构建过程与其表示分离,使得同样的构建过程可以创建不同的表示。 C++实现:流式接口与RAII C++的流式接口可以提供非常直观的建造者API。 完整代码示例 #include
#include
#include

// 产品:复杂的电脑配置
class Computer {
private:
std::string cpu_;
std::string ram_;
std::string storage_;
bool hasGPU_;
bool hasBluetooth_;

public:
// 私有构造函数,强制使用建造者
Computer() = default;

// 内部建造者类
class Builder {
private:
Computer computer_;

public:
Builder& withCPU(const std::string& cpu) {
computer_.cpu_ = cpu;
return *this;
}

Builder& withRAM(const std::string& ram) {
computer_.ram_ = ram;
return *this;
}

Builder& withStorage(const std::string& storage) {
computer_.storage_ = storage;
return *this;
}

Builder& withGPU(bool hasGPU = true) {
computer_.hasGPU_ = hasGPU;
return *this;
}

Builder& withBluetooth(bool hasBluetooth = true) {
computer_.hasBluetooth_ = hasBluetooth;
return *this;
}

std::unique_ptr build() {
// 验证配置
if (computer_.cpu_.empty() || computer_.ram_.empty()) {
throw std::runtime_error(“CPU and RAM are required”);
}
return std::unique_ptr(new Computer(std::move(computer_)));
}
};

// 显示配置
void showSpecs() const {
std::cout << "Computer Specs:" << std::endl; std::cout << " CPU: " << cpu_ << std::endl; std::cout << " RAM: " << ram_ << std::endl; std::cout << " Storage: " << storage_ << std::endl; std::cout << " GPU: " << (hasGPU_ ? "Yes" : "No") << std::endl; std::cout << " Bluetooth: " << (hasBluetooth_ ? "Yes" : "No") << std::endl; } private: // 私有构造函数,只能通过Builder创建 explicit Computer(Computer&& other) : cpu_(std::move(other.cpu_)) , ram_(std::move(other.ram_)) , storage_(std::move(other.storage_)) , hasGPU_(other.hasGPU_) , hasBluetooth_(other.hasBluetooth_) {} }; // 使用示例 int main() { // 流式构建 auto gamingPC = Computer::Builder() .withCPU("Intel i9-13900K") .withRAM("32GB DDR5") .withStorage("2TB NVMe SSD") .withGPU() .withBluetooth() .build(); gamingPC->showSpecs();

// 构建办公电脑
auto officePC = Computer::Builder()
.withCPU(“Intel i5-13400”)
.withRAM(“16GB DDR4”)
.withStorage(“512GB SSD”)
.build();

officePC->showSpecs();

return 0;
}
实战应用与挑战解决
常见难题
:构建过程中的参数验证和依赖关系。
解决方案
:在
build()
方法中集中进行验证,可以返回
std::optional
或抛出异常来处理无效配置。对于复杂验证,可以使用状态机确保构建顺序。
适配器模式(Adapter Pattern)
理论基础
适配器模式将一个类的接口转换成客户希望的另一个接口,使得原本接口不兼容的类可以一起工作。
C++实现:多重继承与组合
C++的多重继承可以优雅地实现适配器模式。
完整代码示例
#include
#include

// 目标接口
class Target {
public:
virtual ~Target() = default;
virtual std::string request() const {
return “Target’s default request”;
}
};

// 需要适配的旧接口
class LegacyService {
public:
std::string specificRequest() const {
return “Legacy service response”;
}
};

// 对象适配器(组合)
class ObjectAdapter : public Target {
private:
std::shared_ptr legacyService_;

public:
ObjectAdapter(std::shared_ptr service)
: legacyService_(service) {}

std::string request() const override {
return “Adapter: ” + legacyService_->specificRequest();
}
};

// 类适配器(多重继承)
class ClassAdapter : public Target, private LegacyService {
public:
std::string request() const override {
return “ClassAdapter: ” + specificRequest();
}
};

// 另一个需要适配的服务
class ThirdPartyService {
public:
std::string differentRequest(int param) const {
return “ThirdParty response with param: ” + std::to_string(param);
}
};

// 适配多个接口
class MultiAdapter : public Target {
private:
std::shared_ptr legacy_;
std::shared_ptr thirdParty_;

public:
MultiAdapter(std::shared_ptr legacy,
std::shared_ptr thirdParty)
: legacy_(legacy), thirdParty_(thirdParty) {}

std::string request() const override {
return legacy_->specificRequest() + ” | ” + thirdParty_->differentRequest(42);
}
};

// 使用示例
int main() {
auto legacy = std::make_shared();
auto thirdParty = std::make_shared();

// 对象适配器
Target* adapter1 = new ObjectAdapter(legacy);
std::cout << adapter1->request() << std::endl; // 类适配器 Target* adapter2 = new ClassAdapter(); std::cout << adapter2->request() << std::endl; // 多接口适配器 Target* adapter3 = new MultiAdapter(legacy, thirdParty); std::cout << adapter3->request() << std::endl; delete adapter1; delete adapter2; delete adapter3; return 0; } 实战应用与挑战解决 常见难题 :接口变化频繁时,适配器维护成本高。 解决方案 :使用代码生成工具自动生成适配器,或采用外观模式(Facade)作为中间层,减少直接依赖。 模板方法模式(Template Method Pattern) 理论基础 模板方法模式定义一个操作中的算法骨架,而将一些步骤延迟到子类中实现。这使得子类可以不改变算法结构即可重定义算法的某些步骤。 C++实现:非虚接口(NVI)模式 C++中推荐使用NVI(Non-Virtual Interface)模式,即公有非虚函数调用私有虚函数。 完整代码示例 #include
#include

// 抽象基类
class Game {
public:
// 模板方法(非虚)
void play() {
initialize();
startPlay();
endPlay();
}

virtual ~Game() = default;

private:
// 基类实现的通用步骤
void initialize() {
std::cout << "Game initialized: Loading resources..." << std::endl; } void endPlay() { std::cout << "Game cleanup: Saving state..." << std::endl; } // 子类需要实现的抽象步骤 virtual void startPlay() = 0; }; // 具体游戏:篮球 class Basketball : public Game { private: void startPlay() override { std::cout << "Basketball: Starting match! Players on court." << std::endl; } }; // 具体游戏:足球 class Football : public Game { private: void startPlay() override { std::cout << "Football: Kickoff! Teams playing." << std::endl; } }; // 带钩子方法的模板方法模式 class NetworkGame { public: // 模板方法 void connectAndPlay() { if (beforeConnect()) { connect(); if (afterConnect()) { playGame(); } disconnect(); } } private: // 钩子方法(有默认实现) virtual bool beforeConnect() { return true; } virtual bool afterConnect() { return true; } // 纯虚方法 virtual void connect() = 0; virtual void playGame() = 0; virtual void disconnect() = 0; }; // 具体网络游戏 class MMORPG : public NetworkGame { private: void connect() override { std::cout << "MMORPG: Connecting to game server..." << std::endl; } void playGame() override { std::cout << "MMORPG: Playing massively multiplayer game!" << std::endl; } void disconnect() override { std::cout << "MMORPG: Disconnecting from server..." << std::endl; } bool beforeConnect() override { std::cout << "MMORPG: Checking account credentials..." << std::endl; return true; } }; // 使用示例 int main() { // 基本模板方法 std::unique_ptr game1 = std::make_unique();
game1->play();

std::unique_ptr game2 = std::make_unique();
game2->play();

// 带钩子的模板方法
std::unique_ptr mmorpg = std::make_unique();
mmorpg->connectAndPlay();

return 0;
}
实战应用与挑战解决
常见难题
:子类可能破坏模板方法的执行流程。
解决方案
:使用NVI模式,将虚函数设为私有或保护,确保模板方法的控制流程不被子类破坏。钩子方法(Hook Methods)提供可选的扩展点。
实战案例:综合应用设计模式解决复杂问题
问题场景
假设我们需要开发一个日志系统,要求:
支持多种输出目标(文件、控制台、网络)
�2. 支持多种日志格式
3. 支持日志级别过滤
4. 支持异步写入
5. 支持动态配置
设计方案
我们将综合运用多个设计模式:
工厂模式
:创建日志处理器
装饰器模式
:添加格式化和过滤功能
观察者模式
:实现异步通知
策略模式
:选择输出策略
单例模式
:全局日志管理器
完整实现代码
#include
#include
#include
#include
#include
#include
#include #include
#include
#include
#include

// 日志级别
enum class LogLevel {
DEBUG,
INFO,
WARNING,
ERROR
};

// 日志消息
struct LogMessage {
LogLevel level;
std::string message;
std::chrono::system_clock::time_point timestamp;

std::string toString() const {
auto time_t = std::chrono::system_clock::to_time_t(timestamp);
std::string levelStr;
switch (level) {
case LogLevel::DEBUG: levelStr = “DEBUG”; break;
case LogLevel::INFO: levelStr = “INFO”; break;
case LogLevel::WARNING: levelStr = “WARNING”; break;
case LogLevel::ERROR: levelStr = “ERROR”; break;
}
return “[” + levelStr + “] ” + message;
}
};

// 抽象日志处理器(策略接口)
class LogHandler {
public:
virtual ~LogHandler() = default;
virtual void handle(const LogMessage& msg) = 0;
};

// 具体处理器:控制台输出
class ConsoleHandler : public LogHandler {
public:
void handle(const LogMessage& msg) override {
std::cout << msg.toString() << std::endl; } }; // 具体处理器:文件输出 class FileHandler : public LogHandler { private: std::ofstream file_; public: FileHandler(const std::string& filename) { file_.open(filename, std::ios::app); } void handle(const LogMessage& msg) override { if (file_.is_open()) { file_ << msg.toString() << std::endl; } } }; // 装饰器基类:日志格式化 class FormatterDecorator : public LogHandler { protected: std::unique_ptr handler_;

public:
FormatterDecorator(std::unique_ptr handler)
: handler_(std::move(handler)) {}

void handle(const LogMessage& msg) override {
handler_->handle(msg);
}
};

// 具体装饰器:JSON格式化
class JSONFormatter : public FormatterDecorator {
public:
using FormatterDecorator::FormatterDecorator;

void handle(const LogMessage& msg) override {
LogMessage formatted = msg;
formatted.message = “{\”message\”: \”” + msg.message + “\”, \”level\”: \”” +
std::to_string(static_cast(msg.level)) + “\”}”;
FormatterDecorator::handle(formatted);
}
};

// 装饰器:日志级别过滤
class LevelFilter : public FormatterDecorator {
private:
LogLevel minLevel_;

public:
LevelFilter(std::unique_ptr handler, LogLevel minLevel)
: FormatterDecorator(std::move(handler)), minLevel_(minLevel) {}

void handle(const LogMessage& msg) override {
if (msg.level >= minLevel_) {
FormatterDecorator::handle(msg);
}
}
};

// 异步日志处理器(装饰器)
class AsyncHandler : public LogHandler {
private:
std::unique_ptr handler_;
std::queue queue_;
std::mutex mutex_;
std::condition_variable cv_;
std::thread worker_;
bool stop_ = false;

public:
AsyncHandler(std::unique_ptr handler)
: handler_(std::move(handler)) {
worker_ = std::thread(&AsyncHandler::processQueue, this);
}

~AsyncHandler() {
{
std::lock_guard lock(mutex_);
stop_ = true;
}
cv_.notify_all();
if (worker_.joinable()) {
worker_.join();
}
}

void handle(const LogMessage& msg) override {
{
std::lock_guard lock(mutex_);
queue_.push(msg);
}
cv_.notify_one();
}

private:
void processQueue() {
while (true) {
std::unique_lock lock(mutex_);
cv_.wait(lock, [this] { return !queue_.empty() || stop_; });

if (stop_ && queue_.empty()) break;

while (!queue_.empty()) {
auto msg = queue_.front();
queue_.pop();
lock.unlock();
handler_->handle(msg);
lock.lock();
}
}
}
};

// 日志管理器(单例 + 工厂)
class Logger {
private:
std::vector> handlers_;
LogLevel globalLevel_ = LogLevel::INFO;

Logger() = default;

public:
static Logger& getInstance() {
static Logger instance;
return instance;
}

// 工厂方法:创建处理器链
void addHandler(std::unique_ptr handler) {
handlers_.push_back(std::move(handler));
}

// 配置工厂
void configureConsole(LogLevel minLevel = LogLevel::INFO) {
auto handler = std::make_unique(
std::make_unique(), minLevel
);
addHandler(std::move(handler));
}

void configureFile(const std::string& filename, LogLevel minLevel = LogLevel::INFO) {
auto handler = std::make_unique(
std::make_unique(filename), minLevel
);
addHandler(std::move(handler));
}

void configureJSONAsync(LogLevel minLevel = LogLevel::INFO) {
auto handler = std::make_unique(
std::make_unique(
std::make_unique()
)
);
addHandler(std::move(handler));
}

// 日志方法
void log(LogLevel level, const std::string& message) {
LogMessage msg{level, message, std::chrono::system_clock::now()};
for (auto& handler : handlers_) {
handler->handle(msg);
}
}

// 便捷方法
void debug(const std::string& msg) { log(LogLevel::DEBUG, msg); }
void info(const std::string& msg) { log(LogLevel::INFO, msg); }
void warning(const std::string& msg) { log(LogLevel::WARNING, msg); }
void error(const std::string& msg) { log(LogLevel::ERROR, msg); }
};

// 使用示例
int main() {
auto& logger = Logger::getInstance();

// 配置多种输出
logger.configureConsole(LogLevel::INFO);
logger.configureFile(“app.log”, LogLevel::DEBUG);
logger.configureJSONAsync(LogLevel::WARNING);

// 测试日志
logger.debug(“This is a debug message”);
logger.info(“Application started successfully”);
logger.warning(“Disk space running low”);
logger.error(“Failed to connect to database”);

// 等待异步日志完成
std::this_thread::sleep_for(std::chrono::milliseconds(100));

return 0;
}
总结与最佳实践
设计模式选择指南
识别问题类型
:首先明确要解决的问题是创建型、结构型还是行为型
评估复杂度
:简单问题可能不需要模式,避免过度设计
考虑C++特性
:充分利用模板、RAII、智能指针等特性
性能考量
:虚函数开销、内存分配、线程安全都需要权衡
C++特有的最佳实践
RAII优先
:使用智能指针管理资源,避免手动delete
模板元编程
:对于性能敏感的场景,使用编译时多态
移动语义
:在模式实现中利用移动语义减少拷贝
constexpr
:对于编译时可计算的配置,使用constexpr
常见陷阱与避免方法
过度工程
:不要为了用模式而用模式
性能陷阱
:虚函数、动态分配在热路径中的影响
线程安全
:确保模式实现是线程安全的
继承滥用
:优先使用组合而非继承
持续学习建议
阅读《设计模式:可复用面向对象软件的基础》
研究开源项目(如Boost、Qt)中的模式应用
实践重构现有代码,识别并应用合适的模式
关注C++标准库中的模式应用(如std::function、std::bind)
通过系统学习和实践这些设计模式,C++开发者可以构建更加健壮、灵活和可维护的软件系统,有效应对各种开发挑战。
# C++设计模式学习与运用 从理论到实战掌握核心技巧 解决软件开发中的常见难题与挑战
引言:设计模式在现代C++开发中的核心地位
在软件开发领域,设计模式(Design Patterns)是解决常见架构问题的最佳实践总结。对于C++开发者而言,掌握设计模式不仅能提升代码质量,还能有效应对软件开发中的各种挑战。设计模式本质上是经过验证的、可复用的解决方案,它们帮助我们构建更加灵活、可维护和可扩展的系统。
C++作为一门支持多范式的编程语言,其强大的特性(如模板、RAII、多态等)为设计模式的实现提供了丰富的手段。然而,C++的复杂性也意味着我们需要更深入地理解如何正确应用这些模式,避免过度设计或误用。
本文将从理论基础出发,深入探讨几种核心设计模式,通过完整的代码示例展示其实战应用,并分析如何利用这些模式解决软件开发中的常见难题。
单例模式(Singleton Pattern)
理论基础
单例模式确保一个类只有一个实例,并提供一个全局访问点。这在需要全局状态管理(如配置管理器、日志系统)时非常有用。
C++实现挑战与最佳实践
在C++中实现单例模式需要考虑线程安全、资源释放和继承等问题。现代C++(C++11及以上)提供了更好的工具来处理这些挑战。
完整代码示例
#include
#include
#include

class Singleton {
private:
// 私有构造函数防止外部实例化
Singleton() = default;

// 删除拷贝构造和赋值操作
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;

// 静态实例(C++11起静态局部变量初始化是线程安全的)
static Singleton* instance;
static std::mutex mutex_;

public:
// 获取实例的静态方法
static Singleton& getInstance() {
// 双重检查锁定模式(Double-Checked Locking Pattern)
if (instance == nullptr) {
std::lock_guard lock(mutex_);
if (instance == nullptr) {
instance = new Singleton();
}
}
return *instance;
}

// 示例业务方法
void doSomething() {
std::cout << "Singleton is doing something!" << std::endl; } // 资源清理(可选,依赖于RAII) static void destroy() { if (instance) { delete instance; instance = nullptr; } } }; // 静态成员定义 Singleton* Singleton::instance = nullptr; std::mutex Singleton::mutex_; // 使用示例 int main() { Singleton& s1 = Singleton::getInstance(); Singleton& s2 = Singleton::getInstance(); s1.doSomething(); // 验证是否为同一实例 std::cout << "s1 address: " << &s1 << std::endl; std::cout << "s2 address: " << &s2 << std::endl; // 清理资源(在实际项目中可依赖RAII自动清理) Singleton::destroy(); return 0; } 实战应用与挑战解决 常见难题 :在多线程环境中,传统单例实现可能导致竞态条件。 解决方案 :使用C++11的静态局部变量初始化(线程安全)或双重检查锁定模式。现代C++推荐使用Meyers’ Singleton(静态局部变量版本),因为它更简洁且线程安全。 进阶考虑 :对于需要继承的单例,可以使用CRTP(奇异递归模板模式)来实现可继承的单例。 工厂模式(Factory Pattern) 理论基础 工厂模式包括简单工厂、工厂方法和抽象工厂。它通过封装对象创建逻辑,实现创建与使用的解耦,便于扩展新的产品类型。 C++实现与模板应用 C++的模板特性可以大大增强工厂模式的灵活性,实现编译时多态。 完整代码示例:抽象工厂 #include
#include
#include
#include
#include

// 产品基类
class Product {
public:
virtual ~Product() = default;
virtual void operation() const = 0;
};

// 具体产品A
class ConcreteProductA : public Product {
public:
void operation() const override {
std::cout << "ConcreteProductA operation" << std::endl; } }; // 具体产品B class ConcreteProductB : public Product { public: void operation() const override { std::cout << "ConcreteProductB operation" << std::endl; } }; // 抽象工厂 class ProductFactory { public: virtual ~ProductFactory() = default; virtual std::unique_ptr create() = 0;
};

// 具体工厂A
class ConcreteFactoryA : public ProductFactory {
public:
std::unique_ptr create() override {
return std::make_unique();
}
};

// 具体工厂B
class ConcreteFactoryB : public ProductFactory {
public:
std::unique_ptr create() override {
return std::make_unique();
}
};

// 注册式工厂(使用函数映射)
class DynamicFactory {
private:
using Creator = std::function()>;
std::unordered_map creators_;

public:
template
void registerProduct(const std::string& name) {
creators_[name] = []() -> std::unique_ptr {
return std::make_unique();
};
}

std::unique_ptr create(const std::string& name) {
auto it = creators_.find(name);
if (it != creators_.end()) {
return it->second();
}
return nullptr;
}
};

// 使用示例
int main() {
// 传统工厂方法
std::unique_ptr factoryA = std::make_unique();
std::unique_ptr productA = factoryA->create();
productA->operation();

// 动态注册工厂
DynamicFactory dynamicFactory;
dynamicFactory.registerProduct(“A”);
dynamicFactory.registerProduct(“B”);

auto product1 = dynamicFactory.create(“A”);
auto product2 = dynamicFactory.create(“B”);

if (product1) product1->operation();
if (product2) product2->operation();

return 0;
}
实战应用与挑战解决
常见难题
:当产品类型频繁变化时,硬编码的工厂难以维护。
解决方案
:使用注册式工厂模式,通过配置或注册机制动态添加产品类型,无需修改工厂代码,符合开闭原则。
观察者模式(Observer Pattern)
理论基础
观察者模式定义了对象间的一对多依赖关系,当一个对象状态改变时,所有依赖者都会收到通知并自动更新。这是事件驱动系统的核心模式。
C++实现:信号与槽机制
现代C++可以使用函数对象和lambda表达式实现轻量级的观察者模式。
完整代码示例
#include
#include
#include
#include

// 前向声明
class Observer;

// 主题(Subject)
class Subject {
private:
std::vector> observers_;
int state_ = 0;

public:
void attach(std::function observer) {
observers_.push_back(observer);
}

void detach(const std::function& observer) {
// 移除特定观察者(需要比较函数对象,实际中可能需要使用ID)
// 这里简化处理,实际中可能需要包装器
}

void setState(int state) {
state_ = state;
notify();
}

int getState() const { return state_; }

private:
void notify() {
for (const auto& observer : observers_) {
observer(state_);
}
}
};

// 观察者(Observer)
class Observer {
public:
virtual ~Observer() = default;
virtual void update(int state) = 0;
};

// 具体观察者
class ConcreteObserver : public Observer {
private:
std::string name_;
public:
ConcreteObserver(const std::string& name) : name_(name) {}

void update(int state) override {
std::cout << name_ << " received update: state = " << state << std::endl; } }; // 使用函数对象的现代实现 class EventManager { private: using Callback = std::function;
std::vector callbacks_;

public:
void subscribe(Callback callback) {
callbacks_.push_back(callback);
}

void notify(const std::string& message) {
for (const auto& callback : callbacks_) {
callback(message);
}
}
};

// 使用示例
int main() {
// 传统观察者模式
Subject subject;
auto obs1 = std::make_shared(“Observer1”);
auto obs2 = std::make_shared(“Observer2”);

subject.attach([obs1](int state) { obs1->update(state); });
subject.attach([obs2](int state) { obs2->update(state); });

subject.setState(10);
subject.setState(20);

// 现代函数对象实现
EventManager eventManager;

// 使用lambda订阅
eventManager.subscribe([](const std::string& msg) {
std::cout << "Lambda1: " << msg << std::endl; }); eventManager.subscribe([](const std::string& msg) { std::cout << "Lambda2: " << msg << std::endl; }); eventManager.notify("Hello Event!"); return 0; } 实战应用与挑战解决 常见难题 :在多线程环境中,观察者通知可能导致死锁或性能瓶颈。 解决方案 :使用异步通知机制或发布-订阅模式。可以结合 std::async 或消息队列实现异步解耦,避免在通知过程中持有锁。 策略模式(Strategy Pattern) 理论基础 策略模式定义一系列算法,将每个算法封装起来,并使它们可以互换。这使得算法的变化独立于使用它的客户端。 C++实现:模板与函数对象 C++的模板和函数对象可以实现零开销的策略模式,避免运行时开销。 完整代码示例 #include
#include
#include
#include

// 策略接口
class SortStrategy {
public:
virtual ~SortStrategy() = default;
virtual void sort(std::vector& data) = 0;
};

// 快速排序策略
class QuickSort : public SortStrategy {
public:
void sort(std::vector& data) override {
std::cout << "Using QuickSort" << std::endl; // 实际排序实现(简化) std::sort(data.begin(), data.end()); } }; // 冒泡排序策略 class BubbleSort : public SortStrategy { public: void sort(std::vector& data) override {
std::cout << "Using BubbleSort" << std::endl; // 实际排序实现(简化) std::sort(data.begin(), data.end()); } }; // 策略上下文 class Context { private: std::unique_ptr strategy_;

public:
Context(std::unique_ptr strategy)
: strategy_(std::move(strategy)) {}

void setStrategy(std::unique_ptr strategy) {
strategy_ = std::move(strategy);
}

void executeStrategy(std::vector& data) {
if (strategy_) {
strategy_->sort(data);
}
}
};

// 模板实现的零开销策略模式
template
class Sorter {
private:
SortFunc sortFunc_;

public:
void sort(std::vector& data) {
sortFunc_(data);
}
};

// 函数对象策略
struct QuickSortFunc {
void operator()(std::vector& data) {
std::cout << "Template QuickSort" << std::endl; std::sort(data.begin(), data.end()); } }; struct MergeSortFunc { void operator()(std::vector& data) {
std::cout << "Template MergeSort" << std::endl; std::sort(data.begin(), data.end()); } }; // 使用示例 int main() { std::vector data = {5, 2, 8, 1, 9};

// 传统策略模式
Context context(std::make_unique());
context.executeStrategy(data);

context.setStrategy(std::make_unique());
context.executeStrategy(data);

// 模板策略模式(编译时多态,无虚函数开销)
Sorter templateSorter;
templateSorter.sort(data);

Sorter templateSorter2;
templateSorter2.sort(data);

return 0;
}
实战应用与挑战解决
常见难题
:运行时策略切换的性能开销。
解决方案
:对于性能敏感的场景,使用模板实现的策略模式(编译时多态)可以消除虚函数调用开销。对于需要运行时动态切换的场景,使用函数对象或
std::function
包装lambda表达式。
装饰器模式(Decorator Pattern)
理论基础
装饰器模式动态地给对象添加额外的职责,而不改变其结构。这是实现开闭原则的经典模式。
C++实现:RAII与组合
C++的RAII特性使得装饰器模式特别优雅,可以自动管理资源。
完整代码示例
#include
#include
#include

// 组件接口
class Component {
public:
virtual ~Component() = default;
virtual std::string operation() const = 0;
};

// 具体组件
class ConcreteComponent : public Component {
public:
std::string operation() const override {
return “ConcreteComponent”;
}
};

// 装饰器基类
class Decorator : public Component {
protected:
std::unique_ptr component_;

public:
Decorator(std::unique_ptr component)
: component_(std::move(component)) {}

std::string operation() const override {
return component_->operation();
}
};

// 具体装饰器A
class ConcreteDecoratorA : public Decorator {
public:
using Decorator::Decorator;

std::string operation() const override {
return “DecoratorA(” + Decorator::operation() + “)”;
}
};

// 具体装饰器B
class ConcreteDecoratorB : public Decorator {
public:
using Decorator::Decorator;

std::string operation() const override {
return “DecoratorB[” + Decorator::operation() + “]”;
}
};

// RAII装饰器:自动计时
class TimingDecorator : public Decorator {
public:
using Decorator::Decorator;

std::string operation() const override {
auto start = std::chrono::high_resolution_clock::now();
std::string result = Decorator::operation();
auto end = std::chrono::high_resolution_clock::now();

auto duration = std::chrono::duration_cast(end – start);
std::cout << "Operation took " << duration.count() << " microseconds" << std::endl; return result; } }; // 使用示例 int main() { // 创建基础组件 auto component = std::make_unique();

// 装饰一层
auto decorated1 = std::make_unique(std::move(component));

// 再装饰一层
auto decorated2 = std::make_unique(std::move(decorated1));

std::cout << decorated2->operation() << std::endl; // RAII装饰器示例 auto timedComponent = std::make_unique(
std::make_unique()
);
std::cout << timedComponent->operation() << std::endl; return 0; } 实战应用与挑战解决 常见难题 :装饰器过多导致对象结构复杂。 解决方案 :使用工厂模式创建装饰器链,或提供流式接口(Builder模式)来简化装饰器的组合。 建造者模式(Builder Pattern) 理论基础 建造者模式将复杂对象的构建过程与其表示分离,使得同样的构建过程可以创建不同的表示。 C++实现:流式接口与RAII C++的流式接口可以提供非常直观的建造者API。 完整代码示例 #include
#include
#include

// 产品:复杂的电脑配置
class Computer {
private:
std::string cpu_;
std::string ram_;
std::string storage_;
bool hasGPU_;
bool hasBluetooth_;

public:
// 私有构造函数,强制使用建造者
Computer() = default;

// 内部建造者类
class Builder {
private:
Computer computer_;

public:
Builder& withCPU(const std::string& cpu) {
computer_.cpu_ = cpu;
return *this;
}

Builder& withRAM(const std::string& ram) {
computer_.ram_ = ram;
return *this;
}

Builder& withStorage(const std::string& storage) {
computer_.storage_ = storage;
return *this;
}

Builder& withGPU(bool hasGPU = true) {
computer_.hasGPU_ = hasGPU;
return *this;
}

Builder& withBluetooth(bool hasBluetooth = true) {
computer_.hasBluetooth_ = hasBluetooth;
return *this;
}

std::unique_ptr build() {
// 验证配置
if (computer_.cpu_.empty() || computer_.ram_.empty()) {
throw std::runtime_error(“CPU and RAM are required”);
}
return std::unique_ptr(new Computer(std::move(computer_)));
}
};

// 显示配置
void showSpecs() const {
std::cout << "Computer Specs:" << std::endl; std::cout << " CPU: " << cpu_ << std::endl; std::cout << " RAM: " << ram_ << std::endl; std::cout << " Storage: " << storage_ << std::endl; std::cout << " GPU: " << (hasGPU_ ? "Yes" : "No") << std::endl; std::cout << " Bluetooth: " << (hasBluetooth_ ? "Yes" : "No") << std::endl; } private: // 私有构造函数,只能通过Builder创建 explicit Computer(Computer&& other) : cpu_(std::move(other.cpu_)) , ram_(std::move(other.ram_)) , storage_(std::move(other.storage_)) , hasGPU_(other.hasGPU_) , hasBluetooth_(other.hasBluetooth_) {} }; // 使用示例 int main() { // 流式构建 auto gamingPC = Computer::Builder() .withCPU("Intel i9-13900K") .withRAM("32GB DDR5") .withStorage("2TB NVMe SSD") .withGPU() .withBluetooth() .build(); gamingPC->showSpecs();

// 构建办公电脑
auto officePC = Computer::Builder()
.withCPU(“Intel i5-13400”)
.withRAM(“16GB DDR4”)
.withStorage(“512GB SSD”)
.build();

officePC->showSpecs();

return 0;
}
实战应用与挑战解决
常见难题
:构建过程中的参数验证和依赖关系。
解决方案
:在
build()
方法中集中进行验证,可以返回
std::optional
或抛出异常来处理无效配置。对于复杂验证,可以使用状态机确保构建顺序。
适配器模式(Adapter Pattern)
理论基础
适配器模式将一个类的接口转换成客户希望的另一个接口,使得原本接口不兼容的类可以一起工作。
C++实现:多重继承与组合
C++的多重继承可以优雅地实现适配器模式。
完整代码示例
#include
#include

// 目标接口
class Target {
public:
virtual ~Target() = default;
virtual std::string request() const {
return “Target’s default request”;
}
};

// 需要适配的旧接口
class LegacyService {
public:
std::string specificRequest() const {
return “Legacy service response”;
}
};

// 对象适配器(组合)
class ObjectAdapter : public Target {
private:
std::shared_ptr legacyService_;

public:
ObjectAdapter(std::shared_ptr service)
: legacyService_(service) {}

std::string request() const override {
return “Adapter: ” + legacyService_->specificRequest();
}
};

// 类适配器(多重继承)
class ClassAdapter : public Target, private LegacyService {
public:
std::string request() const override {
return “ClassAdapter: ” + specificRequest();
}
};

// 另一个需要适配的服务
class ThirdPartyService {
public:
std::string differentRequest(int param) const {
return “ThirdParty response with param: ” + std::to_string(param);
}
};

// 适配多个接口
class MultiAdapter : public Target {
private:
std::shared_ptr legacy_;
std::shared_ptr thirdParty_;

public:
MultiAdapter(std::shared_ptr legacy,
std::shared_ptr thirdParty)
: legacy_(legacy), thirdParty_(thirdParty) {}

std::string request() const override {
return legacy_->specificRequest() + ” | ” + thirdParty_->differentRequest(42);
}
};

// 使用示例
int main() {
auto legacy = std::make_shared();
auto thirdParty = std::make_shared();

// 对象适配器
Target* adapter1 = new ObjectAdapter(legacy);
std::cout << adapter1->request() << std::endl; // 类适配器 Target* adapter2 = new ClassAdapter(); std::cout << adapter2->request() << std::endl; // 多接口适配器 Target* adapter3 = new MultiAdapter(legacy, thirdParty); std::cout << adapter3->request() << std::endl; delete adapter1; delete adapter2; delete adapter3; return 0; } 实战应用与挑战解决 常见难题 :接口变化频繁时,适配器维护成本高。 解决方案 :使用代码生成工具自动生成适配器,或采用外观模式(Facade)作为中间层,减少直接依赖。 模板方法模式(Template Method Pattern) 理论基础 模板方法模式定义一个操作中的算法骨架,而将一些步骤延迟到子类中实现。这使得子类可以不改变算法结构即可重定义算法的某些步骤。 C++实现:非虚接口(NVI)模式 C++中推荐使用NVI(Non-Virtual Interface)模式,即公有非虚函数调用私有虚函数。 完整代码示例 #include
#include

// 抽象基类
class Game {
public:
// 模板方法(非虚)
void play() {
initialize();
startPlay();
endPlay();
}

virtual ~Game() = default;

private:
// 基类实现的通用步骤
void initialize() {
std::cout << "Game initialized: Loading resources..." << std::endl; } void endPlay() { std::cout << "Game cleanup: Saving state..." << std::endl; } // 子类需要实现的抽象步骤 virtual void startPlay() = 0; }; // 具体游戏:篮球 class Basketball : public Game { private: void startPlay() override { std::cout << "Basketball: Starting match! Players on court." << std::endl; } }; // 具体游戏:足球 class Football : public Game { private: void startPlay() override { std::cout << "Football: Kickoff! Teams playing." << std::endl; } }; // 带钩子方法的模板方法模式 class NetworkGame { public: // 模板方法 void connectAndPlay() { if (beforeConnect()) { connect(); if (afterConnect()) { playGame(); } disconnect(); } } private: // 钩子方法(有默认实现) virtual bool beforeConnect() { return true; } virtual bool afterConnect() { return true; } // 纯虚方法 virtual void connect() = 0; virtual void playGame() = 0; virtual void disconnect() = 0; }; // 具体网络游戏 class MMORPG : public NetworkGame { private: void connect() override { std::cout << "MMORPG: Connecting to game server..." << std::endl; } void playGame() override { std::cout << "MMORPG: Playing massively multiplayer game!" << std::endl; } void disconnect() override { std::cout << "MMORPG: Disconnecting from server..." << std::endl; } bool beforeConnect() override { std::cout << "MMORPG: Checking account credentials..." << std::endl; return true; } }; // 使用示例 int main() { // 基本模板方法 std::unique_ptr game1 = std::make_unique();
game1->play();

std::unique_ptr game2 = std::make_unique();
game2->play();

// 带钩子的模板方法
std::unique_ptr mmorpg = std::make_unique();
mmorpg->connectAndPlay();

return 0;
}
实战应用与挑战解决
常见难题
:子类可能破坏模板方法的执行流程。
解决方案
:使用NVI模式,将虚函数设为私有或保护,确保模板方法的控制流程不被子类破坏。钩子方法(Hook Methods)提供可选的扩展点。
实战案例:综合应用设计模式解决复杂问题
问题场景
假设我们需要开发一个日志系统,要求:
支持多种输出目标(文件、控制台、网络)
支持多种日志格式
支持日志级别过滤
支持异步写入
支持动态配置
设计方案
我们将综合运用多个设计模式:
工厂模式
:创建日志处理器
装饰器模式
:添加格式化和过滤功能
观察者模式
:实现异步通知
策略模式
:选择输出策略
单例模式
:全局日志管理器
完整实现代码
#include
#include
#include
#include
#include
#include
#include #include
#include
#include
#include

// 日志级别
enum class LogLevel {
DEBUG,
INFO,
WARNING,
ERROR
};

// 日志消息
struct LogMessage {
LogLevel level;
std::string message;
std::chrono::system_clock::time_point timestamp;

std::string toString() const {
auto time_t = std::chrono::system_clock::to_time_t(timestamp);
std::string levelStr;
switch (level) {
case LogLevel::DEBUG: levelStr = “DEBUG”; break;
case LogLevel::INFO: levelStr = “INFO”; break;
case LogLevel::WARNING: levelStr = “WARNING”; break;
case LogLevel::ERROR: levelStr = “ERROR”; break;
}
return “[” + levelStr + “] ” + message;
}
};

// 抽象日志处理器(策略接口)
class LogHandler {
public:
virtual ~LogHandler() = default;
virtual void handle(const LogMessage& msg) = 0;
};

// 具体处理器:控制台输出
class ConsoleHandler : public LogHandler {
public:
void handle(const LogMessage& msg) override {
std::cout << msg.toString() << std::endl; } }; // 具体处理器:文件输出 class FileHandler : public LogHandler { private: std::ofstream file_; public: FileHandler(const std::string& filename) { file_.open(filename, std::ios::app); } void handle(const LogMessage& msg) override { if (file_.is_open()) { file_ << msg.toString() << std::endl; } } }; // 装饰器基类:日志格式化 class FormatterDecorator : public LogHandler { protected: std::unique_ptr handler_;

public:
FormatterDecorator(std::unique_ptr handler)
: handler_(std::move(handler)) {}

void handle(const LogMessage& msg) override {
handler_->handle(msg);
}
};

// 具体装饰器:JSON格式化
class JSONFormatter : public FormatterDecorator {
public:
using FormatterDecorator::FormatterDecorator;

void handle(const LogMessage& msg) override {
LogMessage formatted = msg;
formatted.message = “{\”message\”: \”” + msg.message + “\”, \”level\”: \”” +
std::to_string(static_cast(msg.level)) + “\”}”;
FormatterDecorator::handle(formatted);
}
};

// 装饰器:日志级别过滤
class LevelFilter : public FormatterDecorator {
private:
LogLevel minLevel_;

public:
LevelFilter(std::unique_ptr handler, LogLevel minLevel)
: FormatterDecorator(std::move(handler)), minLevel_(minLevel) {}

void handle(const LogMessage& msg) override {
if (msg.level >= minLevel_) {
FormatterDecorator::handle(msg);
}
}
};

// 异步日志处理器(装饰器)
class AsyncHandler : public LogHandler {
private:
std::unique_ptr handler_;
std::queue queue_;
std::mutex mutex_;
std::condition_variable cv_;
std::thread worker_;
bool stop_ = false;

public:
AsyncHandler(std::unique_ptr handler)
: handler_(std::move(handler)) {
worker_ = std::thread(&AsyncHandler::processQueue, this);
}

~AsyncHandler() {
{
std::lock_guard lock(mutex_);
stop_ = true;
}
cv_.notify_all();
if (worker_.joinable()) {
worker_.join();
}
}

void handle(const LogMessage& msg) override {
{
std::lock_guard lock(mutex_);
queue_.push(msg);
}
cv_.notify_one();
}

private:
void processQueue() {
while (true) {
std::unique_lock lock(mutex_);
cv_.wait(lock, [this] { return !queue_.empty() || stop_; });

if (stop_ && queue_.empty()) break;

while (!queue_.empty()) {
auto msg = queue_.front();
queue_.pop();
lock.unlock();
handler_->handle(msg);
lock.lock();
}
}
}
};

// 日志管理器(单例 + 工厂)
class Logger {
private:
std::vector> handlers_;
LogLevel globalLevel_ = LogLevel::INFO;

Logger() = default;

public:
static Logger& getInstance() {
static Logger instance;
return instance;
}

// 工厂方法:创建处理器链
void addHandler(std::unique_ptr handler) {
handlers_.push_back(std::move(handler));
}

// 配置工厂
void configureConsole(LogLevel minLevel = LogLevel::INFO) {
auto handler = std::make_unique(
std::make_unique(), minLevel
);
addHandler(std::move(handler));
}

void configureFile(const std::string& filename, LogLevel minLevel = LogLevel::INFO) {
auto handler = std::make_unique(
std::make_unique(filename), minLevel
);
addHandler(std::move(handler));
}

void configureJSONAsync(LogLevel minLevel = LogLevel::INFO) {
auto handler = std::make_unique(
std::make_unique(
std::make_unique()
)
);
addHandler(std::move(handler));
}

// 日志方法
void log(LogLevel level, const std::string& message) {
LogMessage msg{level, message, std::chrono::system_clock::now()};
for (auto& handler : handlers_) {
handler->handle(msg);
}
}

// 便捷方法
void debug(const std::string& msg) { log(LogLevel::DEBUG, msg); }
void info(const std::string& msg) { log(LogLevel::INFO, msg); }
void warning(const std::string& msg) { log(LogLevel::WARNING, msg); }
void error(const std::string& msg) { log(LogLevel::ERROR, msg); }
};

// 使用示例
int main() {
auto& logger = Logger::getInstance();

// 配置多种输出
logger.configureConsole(LogLevel::INFO);
logger.configureFile(“app.log”, LogLevel::DEBUG);
logger.configureJSONAsync(LogLevel::WARNING);

// 测试日志
logger.debug(“This is a debug message”);
logger.info(“Application started successfully”);
logger.warning(“Disk space running low”);
logger.error(“Failed to connect to database”);

// 等待异步日志完成
std::this_thread::sleep_for(std::chrono::milliseconds(100));

return 0;
}
总结与最佳实践
设计模式选择指南
识别问题类型
:首先明确要解决的问题是创建型、结构型还是行为型
评估复杂度
:简单问题可能不需要模式,避免过度设计
考虑C++特性
:充分利用模板、RAII、智能指针等特性
性能考量
:虚函数开销、内存分配、线程安全都需要权衡
C++特有的最佳实践
RAII优先
:使用智能指针管理资源,避免手动delete
模板元编程
:对于性能敏感的场景,使用编译时多态
移动语义
:在模式实现中利用移动语义减少拷贝
constexpr
:对于编译时可计算的配置,使用constexpr
常见陷阱与避免方法
过度工程
:不要为了用模式而用模式
性能陷阱
:虚函数、动态分配在热路径中的影响
线程安全
:确保模式实现是线程安全的
继承滥用
:优先使用组合而非继承
持续学习建议
阅读《设计模式:可复用面向对象软件的基础》
研究开源项目(如Boost、Qt)中的模式应用
实践重构现有代码,识别并应用合适的模式
关注C++标准库中的模式应用(如std::function、std::bind)
通过系统学习和实践这些设计模式,C++开发者可以构建更加健壮、灵活和可维护的软件系统,有效应对各种开发挑战。