状态模式:
- 书中原话《大话设计模式》:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类
- 状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。
- 把状态的判断逻辑转移到表示不同状态的一系列类当中,可以把复杂的判断逻辑简化。
- 将特定的状态相关的行为都放入一个对象中,由于所有与状态相关的代码都存在于某个类中,所以通过定义新的子类可以很容易的增加新的状态和转换
- 消除庞大的条件分支语句
- 当一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,就可以考虑使用状态模式了
下面给出简单实现思路,不列出具体逻辑判断,自己琢磨的,也不知道对不对
#include <iostream>
#include <string>
using namespace std;
class Context;
class State
{
public:
State() {}
virtual ~State() {}
virtual void test(Context *c) = 0;
};
class StateA : public State
{
public:
StateA() {}
virtual ~StateA() {}
void test(Context *c);
};
class StateB : public State
{
public:
StateB() {}
virtual ~StateB() {}
void test(Context *c);
};
class Context
{
public:
State *c;
Context(State *_c):c(_c){}
void request()
{
c->test(this);
}
};
void StateA::test(Context *c)
{
//可以在这个地方加入逻辑判断,改变状态
/*
if(...)
{
c->c = new 某状态子类;
}
else if(...)
{
c->c = new 某状态子类;
}
*/
cout << "change state to B" << endl;
c->c = new StateB;
delete this;
}
void StateB::test(Context *c)
{
//可以在这个地方加入逻辑判断,改变状态
/*
if(...)
{
c->c = new 某状态子类;
}
else if(...)
{
c->c = new 某状态子类;
}
*/
cout << "change state to A" << endl;
c->c = new StateA;
delete this;
}
int main()
{
Context *c = new Context(new StateA);
c->request();
c->request();
c->request();
c->request();
getchar();
return 0;
}
