状态模式:
当一个对象状态转换的条件表达式过于复杂时,状态模式通过把状态的判断逻辑转移到表示不同的状态的一系列类中,从而把复杂判断逻辑简化。通过添加新的子类可以很容易的增加新的状态。
类图:
关键代码:
// State.h
class Context;
class State
{
public:
State();
virtual ~State();
virtual void handle(Context * c);
};
State::State(){
}
State::~State(){
}
void State::handle(Context * c){
}
// Context.h
#include "State.h"
#include "ConcreteStateA.h"
class Context
{
public:
Context();
virtual ~Context();
void changeState(State * st);
void request();
private:
State *m_pState;
};
Context::Context(){
m_pState = ConcreteStateA::Instance();
}
Context::~Context(){
}
void Context::changeState(State * st){
m_pState = st;
}
void Context::request(){
m_pState->handle(this);
}
// ConcreteStateA.h
#include "State.h"
#include "Context.h"
#include <iostream>
class ConcreteStateA : public State
{
public:
virtual ~ConcreteStateA();
static State * Instance();
virtual void handle(Context * c);
private:
ConcreteStateA();
static State * m_pState;
};
State * ConcreteStateA::m_pState = NULL;
ConcreteStateA::ConcreteStateA(){
}
ConcreteStateA::~ConcreteStateA(){
}
State * ConcreteStateA::Instance()
{
if ( NULL == m_pState)
{
m_pState = new ConcreteStateA();
}
return m_pState;
}
void ConcreteStateA::handle(Context * c){
cout << "doing something in State A.\n done,change state to B" << endl;
c->changeState(ConcreteStateB::Instance());
}
// client
#include <iostream>
#include "Context.h"
#include "ConcreteStateA.h"
#include "ConcreteStateB.h"
using namespace std;
int main(int argc, char *argv[])
{
Context * c = new Context(ConcreteStateA::Instance());
c->request();
c->request();
c->request();
delete c;
return 0;
}