模式定义
状态模式(State Pattern)是一种行为型设计模式,允许对象在其内部状态改变时动态调整行为,使对象的行为看起来像是修改了其类。该模式通过将状态相关的逻辑封装到独立的类中,避免了复杂的条件分支,提升代码的可维护性和扩展性。
模式结构
上下文类(Context)
- 维护当前状态对象的引用,定义客户端交互接口(如数控机床的启动、暂停操作)。
抽象状态类(State) - 声明状态共有的接口方法(如
handleStart
、handlePause
),定义状态间的行为规范。
具体状态类(ConcreteState) - 实现抽象状态接口,定义特定状态下的行为逻辑(如待机、加工、暂停状态),并处理状态转换。
适用场景
对象行为依赖状态:如数控机床在不同运行阶段(待机/加工/暂停)需执行不同操作。
减少条件分支:将复杂的if-else
逻辑拆解为独立状态类。
动态状态切换:运行时根据事件(如用户指令)灵活调整行为。
C++示例(数控系统场景)
场景说明:
数控机床控制器根据当前状态(待机、加工、暂停)响应操作请求,行为随状态动态变化。
cpp
#include
#include
// 前向声明
class CNCMachine;
// 抽象状态类
class MachiningState {
public:
virtual ~MachiningState() = default;
virtual void handleStart(CNCMachine& context) const = 0;
virtual void handlePause(CNCMachine& context) const = 0;
virtual void handleResume(CNCMachine& context) const = 0;
};
// 上下文类:数控机床控制器
class CNCMachine {
private:
std::unique_ptr currentState_;
public:
explicit CNCMachine();
// 设置新状态
void setState(std::unique_ptr newState) {
currentState_ = std::move(newState);
}
// 客户端接口:触发操作
void start() {
currentState_->handleStart(*this);
}
void pause() {
currentState_->handlePause(*this);
}
void resume() {
currentState_->handleResume(*this);
}
};
// 具体状态1:待机状态
class IdleState : public MachiningState {
public:
void handleStart(CNCMachine& context) const override {
std::cout << "从待机状态启动:开始加工..." << std::endl;
context.setState(std::make_unique());
}
void handlePause(CNCMachine&) const override {
std::cout << "错误:待机状态下无法暂停!" << std::endl;
}
void handleResume(CNCMachine&) const override {
std::cout << "错误:待机状态下无法恢复!" << std::endl;
}
};
// 具体状态2:加工状态
class ProcessingState : public MachiningState {
public:
void handleStart(CNCMachine&) const override {
std::cout << "警告:已在加工中!" << std::endl;
}
void handlePause(CNCMachine& context) const override {
std::cout << "暂停加工..." << std::endl;
context.setState(std::make_unique());
}
void handleResume(CNCMachine&) const override {
std::cout << "错误:加工中无需恢复!" << std::endl;
}
};
// 具体状态3:暂停状态
class PausedState : public MachiningState {
public:
void handleStart(CNCMachine&) const override {
std::cout << "错误:请先恢复加工!" << std::endl;
}
void handlePause(CNCMachine&) const override {
std::cout << "错误:已处于暂停状态!" << std::endl;
}
void handleResume(CNCMachine& context) const override {
std::cout << "恢复加工..." << std::endl;
context.setState(std::make_unique());
}
};
// 初始化上下文状态
CNCMachine::CNCMachine() : currentState_(std::make_unique()) {}
// 客户端使用示例
int main() {
CNCMachine machine;
machine.start(); // 输出:从待机状态启动... [3][6]
machine.pause(); // 输出:暂停加工... [3][6]
machine.resume(); // 输出:恢复加工... [3][6]
machine.pause(); // 输出:暂停加工... [3][6]
machine.start(); // 输出:错误:请先恢复加工! [3][6]
}
实现要点
状态转换逻辑内聚:具体状态类负责判断何时切换到其他状态(如ProcessingState
在handlePause
中切换到PausedState
)。
上下文与状态解耦:CNCMachine
仅通过setState
切换状态,不直接处理行为逻辑。
扩展性:新增状态(如急停状态)只需添加新的ConcreteState
类,无需修改现有代码。
通过状态模式,数控系统的行为与状态管理变得清晰且易于维护,符合开闭原则。