- do {
- char ch = *itChar;
- switch(ch)
- {
- case '<':
- switch(State)
- {
- case 开始状态:
- 开始处理…
- 切换到左标签状态
- break;
- case 标签值状态:
- 标签值状态处理…
- break;
- }
- break;
- case '>':
- switch(State)
- {
- case 左标签名状态:
- 左标签名状态处理…
- 切换到标签名状态
- break;
- case 右标签名状态:
- 右标签名状态处理…
- break;
- }
- break;
- …
- }
- } while(字符串读取未结束)
//state.h
#ifndef _STATE_H_
#define _STATE_H_
class Context; //前置声明
class State
{
public:
State();
virtual ~State();
virtual void Handle(Context* ) = 0;
protected:
bool ChangeState(Context* con,State* st);
};
class ConcreteStateA:public State
{
public:
ConcreteStateA() {};
virtual ~ConcreteStateA() {};
virtual void Handle(Context* );
};
class ConcreteStateB:public State
{
public:
ConcreteStateB() {};
virtual ~ConcreteStateB() {};
virtual void Handle(Context* );
};
#endif //~_STATE_H_
|
//state.cpp
#include "Context.h"
#include <iostream>
using namespace std;
void State::Handle(Context* con)
{
cout<<"State::.."<<endl;
}
bool State::ChangeState(Context* con,State* st)
{
con->ChangeState(st);
return true;
}
void ConcreteStateA::Handle(Context* con)
{
cout<<"ConcreteStateA::OperationInterface......"<<endl;
this->ChangeState(con,new ConcreteStateB());
}
void ConcreteStateB::Handle(Context* con)
{
cout<<"ConcreteStateB::OperationInterface......"<<endl;
this->ChangeState(con,new ConcreteStateA());
}
|
//context.h
#ifndef _CONTEXT_H_
#define _CONTEXT_H_
class State;
class Context
{
public:
Context();
Context(State* state);
~Context();
void Request();
protected:
private:
friend class State; //表明在State类中可以访问Context类的private字段
bool ChangeState(State* state);
private:
State* _state;
};
#endif //~_CONTEXT_H_
|
//context.cpp
#include "stdafx.h"
#include "Context.h"
#include "State.h"
Context::Context()
{
}
Context::Context(State* state)
{
this->_state = state;
}
Context::~Context()
{
delete _state;
}
void Context::Request()
{
_state->Handle(this);
}
bool Context::ChangeState(State* state)
{
if (_state) delete _state;
_state = state;
return true;
}
|
//测试代码
int StateTest()
{
State* st = new ConcreteStateA();
Context* con = new Context(st);
con->Request();
con->Request();
con->Request();
if (con != NULL)
delete con;
if (st != NULL)
st = NULL;
return 0;
}
|