C++ 写一个状态模式的完整代码
时间: 2024-10-11 10:03:43 浏览: 31
状态模式是一种行为设计模式,它封装了对象在其生命周期的不同状态,并通过改变状态来改变对象的行为。在C++中,我们可以创建一个基类State,然后定义一组子类表示不同的状态,以及一个Context类来维护状态并触发相应的操作。
下面是一个简单的状态模式实现示例:
```cpp
#include <iostream>
enum class ConnectionState { Disconnected, Connecting, Online };
class ConnectionStateMachine {
private:
ConnectionState state;
public:
ConnectionStateMachine() : state(ConnectionState::Disconnected) {}
// 状态接口
virtual void connect() = 0;
virtual void disconnect() = 0;
virtual void sendData() = 0;
// 抽象状态实现
class DisconnectedState : public ConnectionStateMachine {
public:
void connect() override {
std::cout << "Connecting..." << std::endl;
state = ConnectionState::Connecting;
}
void disconnect() override {
std::cout << "Disconnected" << std::endl;
state = ConnectionState::Disconnected;
}
void sendData() override {
throw std::runtime_error("Not connected");
}
};
class ConnectingState : public ConnectionStateMachine {
public:
void connect() override {
std::cout << "Already connecting" << std::endl;
}
void disconnect() override {
state = ConnectionState::Disconnected;
}
void sendData() override {
std::cout << "Sending data in connecting state" << std::endl;
}
};
class OnlineState : public ConnectionStateMachine {
public:
void connect() override {
std::cout << "Already online" << std::endl;
}
void disconnect() override {
state = ConnectionState::Disconnected;
}
void sendData() override {
std::cout << "Sending data" << std::endl;
}
};
// 根据当前状态选择正确的状态对象
void setState(ConnectionState newState) {
if (newState == state)
return;
switch (state) {
case ConnectionState::Disconnected:
state = ConnectionState::Connecting;
break;
case ConnectionState::Connecting:
state = ConnectionState::Online;
break;
default:
// 如果尝试切换到其他非预期状态,保持连接状态
break;
}
state = newState;
if (state == ConnectionState::Connecting) {
ConnectingState *connecting = new ConnectingState();
delete this;
connecting->setState(state);
} else if (state == ConnectionState::Online) {
OnlineState *online = new OnlineState();
delete this;
online->setState(state);
}
}
};
int main() {
ConnectionStateMachine machine;
machine.setState(ConnectionState::Connecting);
machine.connect(); // 输出: Already connecting
machine.sendData(); // 输出: Sending data in connecting state
machine.setState(ConnectionState::Online);
machine.disconnect(); // 输出: Disconnecting...
return 0;
}
```
在这个例子中,`ConnectionStateMachine`是上下文,`DisconnectedState`, `ConnectingState`, 和 `OnlineState` 分别代表不同的状态,每个状态都有对应的处理行为。在main函数中,我们通过`setState`动态地改变了状态机的状态。
阅读全文