1 Star 0 Fork 621

Beqee/DesignPattern

forked from Micooz/DesignPattern 
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
StatePattern.cpp 1.51 KB
一键复制 编辑 原始数据 按行查看 历史
#include <iostream>
using namespace std;
class State;
class ConcreteStateB;
class ConcreteStateA;
class State {
public:
virtual void OperationChangeState(Context*) = 0;
virtual void OperationInterface(Context*) = 0;
virtual ~State() { }
protected:
bool ChangeState(Context* con, State *st) {
con->ChangeState(st);
}
};
class ConcreteStateA :public State {
public:
void OperationChangeState(Context* con) {
OperationInterface(con);
this->ChangeState(con, new ConcreteStateB());
}
void OperationInterface(Context* con) {
cout << "ConcreteStateA::OperationInterface..." << endl;
}
};
class ConcreteStateB :public State {
public:
void OperationChangeState(Context* con) {
OperationInterface(con);
this->ChangeState(con, new ConcreteStateA());
}
void OperationInterface(Context* con) {
cout << "ConcreteStateB::OperationInterface..." << endl;
}
};
class Context {
public:
Context(State* st) {
_st = st;
}
void OperationInterface() {
_st->OperationInterface(this);
}
void OperationChangeState() {
_st->OperationInterface(this);
}
private:
friend class State;
bool ChangeState(State* st) {
_st = st;
return true;
}
State *_st;
};
int main() {
State *st = new ConcreteStateA();
Context *con = new Context(st);
con->OperationInterface();
con->OperationInterface();
con->OperationInterface();
delete con;
delete st;
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/Beqee/DesignPattern.git
git@gitee.com:Beqee/DesignPattern.git
Beqee
DesignPattern
DesignPattern
master

搜索帮助