State.cpp
#include "State.h"
#include "Context.h"
#include <iostream>
using namespace std;
State::State(){
}
State::~State(){
}
void State::ChangeState(Context* con,State* st){
con->ChangeState(st);
}
///
ConcreteStateA::ConcreteStateA(){
}
ConcreteStateA::~ConcreteStateA(){
}
void ConcreteStateA::Handle(Context* con){
con->OperationForStateA();
cout<<":: State change from A to B"<<endl;
State::ChangeState(con,new ConcreteStateB());
}
///
ConcreteStateB::ConcreteStateB(){
}
ConcreteStateB::~ConcreteStateB(){
}
void ConcreteStateB::Handle(Context* con){
con->OperationForStateB();
cout<<":: State change from B to A"<<endl;
State::ChangeState(con,new ConcreteStateA());
}
main.cpp
#include "Context.h"
#include "State.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[]){
State* st = new ConcreteStateA();
Context* con = new Context(st);
con->Handle();
con->Handle();
con->Handle();
if (con != NULL)
delete con;
if (st != NULL)
st = NULL;
return 0;
}
可以看到在测试程序中,三次调用 con->Handle(),因为 con 状态的不同,可以得到以下的输出:
Do operation in State A :: State change from A to B
Do operation in State B :: State change from B to A
Do operation in State A :: State change from A to B
适用性
一个对象的行为取决于它的状态, 并且它必须在运行时刻根据状态改变它的行为。
一个操作中含有庞大的多分支的条件语句,且这些分支依赖于该对象的状态。这个状态通常用一个或多个枚举常量表示。通常, 有多个操作包含这一相同的条件结构。S t a t e模式将每一个条件分支放入一个独立的类中。这使得你可以根据对象自身的情况将对象的状态作为一个对象,这一对象可以不依赖于其他对象而独立变化。










