23种设计模式 - 策略模式
模式定义
策略模式(Strategy Pattern)是一种行为型设计模式,它定义了一系列可互换的算法,并将每个算法封装成独立类,使得算法可以独立于客户端变化。该模式的核心思想是解耦算法的定义与使用,适用于需要动态切换行为或算法的场景,例如数控系统中的加工策略选择。
模式结构
抽象策略类(Strategy)
- 定义算法的公共接口(如
execute()
),声明策略的通用行为。
具体策略类(ConcreteStrategy) - 实现抽象策略接口,封装具体算法(如数控系统中的高速切削、精密切削等策略)。
上下文类(Context) - 持有策略对象的引用,通过接口调用具体策略的算法。
适用场景
算法需要动态切换:如数控系统根据材料硬度自动选择切削策略。
避免多重条件分支:将复杂的条件逻辑拆分为独立的策略类。
隐藏算法实现细节:保护数控系统的核心加工逻辑不被客户端直接依赖。
C++示例(数控系统场景)
场景说明:
数控机床根据加工需求(如材料类型)动态切换切削策略,例如高速切削和精密切削。
#include
#include
// 抽象策略类:切削策略接口
class MachiningStrategy {
public:
virtual ~MachiningStrategy() = default;
virtual void execute() const = 0; // 执行切削操作
};
// 具体策略1:高速切削策略
class HighSpeedStrategy : public MachiningStrategy {
public:
void execute() const override {
std::cout << "执行高速切削:转速 2000 RPM,进给速度 500 mm/min" << std::endl;
}
};
// 具体策略2:精密切削策略
class PrecisionStrategy : public MachiningStrategy {
public:
void execute() const override {
std::cout << "执行精密切削:转速 800 RPM,进给速度 100 mm/min" << std::endl;
}
};
// 上下文类:数控机床控制器
class CNCMachine {
private:
std::unique_ptr strategy_; // 持有策略对象
public:
void setStrategy(std::unique_ptr strategy) {
strategy_ = std::move(strategy);
}
void performCutting() const {
if (strategy_) {
strategy_->execute();
} else {
std::cout << "未设置切削策略!" << std::endl;
}
}
};
// 客户端使用示例
int main() {
CNCMachine machine;
// 使用高速切削策略
machine.setStrategy(std::make_unique());
machine.performCutting(); // 输出高速切削参数[1][8]
// 切换为精密切削策略
machine.setStrategy(std::make_unique());
machine.performCutting(); // 输出精密切削参数[3][6]
return 0;
}
代码解析
策略接口与实现
MachiningStrategy
定义切削操作的通用接口,HighSpeedStrategy
和PrecisionStrategy
分别实现具体算法。
动态切换策略CNCMachine
通过setStrategy
方法在运行时切换策略,调用performCutting()
时执行当前策略。
智能指针管理- 使用
std::unique_ptr
自动管理策略对象生命周期,避免内存泄漏。
优势与扩展
扩展性:新增切削策略只需添加具体策略类,无需修改数控机床控制器。
复用性:策略类可被多个数控系统组件共享(如刀具库管理模块)。
符合开闭原则:算法变化通过新增类实现,而非修改已有代码。