在现代C++中,以下架构设计模式被广泛应用:
1. 工厂模式
核心思想 :封装对象的创建逻辑,通过统一接口生成不同类型对象。
现代实现:
- 使用智能指针(如
std::unique_ptr)管理资源 - 结合模板或
std::function实现泛型工厂
cpp
class IProduct {
public:
virtual ~IProduct() = default;
virtual void operation() = 0;
};
template <typename T>
std::unique_ptr<IProduct> createProduct() {
return std::make_unique<T>();
}
2. RAII(资源获取即初始化)
核心思想 :通过对象生命周期自动管理资源(内存、文件句柄等)。
现代特性:
- 智能指针(
std::unique_ptr,std::shared_ptr) - 移动语义(避免深拷贝)
cpp
class FileHandler {
public:
FileHandler(const std::string& path) : handle(openFile(path)) {}
~FileHandler() { closeFile(handle); }
// 禁用拷贝,启用移动
FileHandler(FileHandler&&) = default;
private:
HandleType handle;
};
3. 观察者模式
核心思想 :对象状态变化时自动通知依赖它的对象。
现代优化:
- 使用
std::function替代虚函数接口 - 结合
std::vector存储观察者
cpp
class Subject {
public:
void addObserver(std::function<void()> obs) {
observers.push_back(obs);
}
void notify() {
for (auto& obs : observers) obs();
}
private:
std::vector<std::function<void()>> observers;
};
4. 策略模式
核心思想 :将算法封装为独立对象,支持运行时切换。
现代实现:
- 通过
std::function和 Lambda 表达式简化策略定义
cpp
class Context {
public:
void setStrategy(std::function<void()> strategy) {
this->strategy = strategy;
}
void execute() { strategy(); }
private:
std::function<void()> strategy;
};
// 使用示例
Context ctx;
ctx.setStrategy([] { /* 策略A逻辑 */ });
ctx.execute();
5. 单例模式
核心思想 :确保类仅有一个实例,并提供全局访问点。
线程安全改进:
- C++11 后的
std::call_once保证初始化原子性
cpp
class Singleton {
public:
static Singleton& getInstance() {
static std::once_flag flag;
std::call_once(flag, [] { instance.reset(new Singleton); });
return *instance;
}
private:
static std::unique_ptr<Singleton> instance;
Singleton() = default;
};
6. 适配器模式
核心思想 :转换不兼容接口为目标接口。
现代应用:
- 结合模板实现泛型适配
- 使用
std::bind包装旧接口
cpp
class LegacySystem {
public:
void legacyOperation(int x) { /*...*/ }
};
class Adapter {
public:
Adapter(LegacySystem& legacy) : adaptee(legacy) {}
void modernOperation() {
std::bind(&LegacySystem::legacyOperation, &adaptee, 42)();
}
private:
LegacySystem& adaptee;
};
总结
现代C++通过以下特性优化传统设计模式:
- 智能指针(自动资源管理)
- Lambda 和
std::function(减少虚函数开销) - 移动语义(提升性能)
- 模板(增强泛化能力)
选择模式时需结合具体场景,避免过度设计。