代码片断 2:State.cpp
//State.cpp
#include "State.h"
#include "Context.h"
#include <iostream>
using namespace std;
State::State(){
}
State::~State(){
}
void State::OperationInterface(Context* con){
cout<<"State::.."<<endl;
}
bool State::ChangeState(Context* con,State* st){
con->ChangeState(st);
return true;
}
void State::OperationChangeState(Context* con){
}
///
ConcreteStateA::ConcreteStateA(){
}
ConcreteStateA::~ConcreteStateA(){
}
void ConcreteStateA::OperationInterface(Context* con){
cout<<"ConcreteStateA::OperationInterface
......"<<endl;
}
void ConcreteStateA::OperationChangeState(Context* con){
OperationInterface(con);
this->ChangeState(con,new ConcreteStateB());
}
///
ConcreteStateB::ConcreteStateB(){
}
ConcreteStateB::~ConcreteStateB(){
}
void ConcreteStateB::OperationInterface(Context* con){
cout<<"ConcreteStateB::OperationInterface......"<<endl;
}
void ConcreteStateB::OperationChangeState(Context* con){
OperationInterface(con);
this->ChangeState(con,new ConcreteStateA());
}
代码片断 3:Context.h
//context.h
#ifndef _CONTEXT_H_
#define _CONTEXT_H_
class State;
/**
*
**/
class Context{
public:
Context();
Context(State* state);
~Context();
void OprationInterface();
void OperationChangState();
protected:
private:
friend class State; //表明在 State 类中可以访问 Context 类的 private 字段
bool ChangeState(State* state);
private:
State* _state;
};
#endif //~_CONTEXT_H_
代码片断 4:Context.cpp
//context.cpp
#include "Context.h"
#include "State.h"
Context::Context(){
}
Context::Context(State* state){
this->_state = state;
}
Context::~Context(){
delete _state;
}
void Context::OprationInterface(){
_state->OperationInterface(this);
}
bool Context::ChangeState(State* state){
///_state->ChangeState(this,state);
this->_state = state;
return true;
}
void Context::OperationChangState(){
_state->OperationChangeState(this);
}
代码片断 5:main.cpp
//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->OperationChangState();
con->OperationChangState();
con->OperationChangState();
if (con != NULL)
delete con;
if (st != NULL)
st = NULL;
return 0;
}
代码说明:状态模式在实现中,有两个关键点:
1.将状态声明为 Context 的友元类(friend class),其作用是让状态模式访问 Context的 protected 接口 ChangeSate()。










