#ifndef _CONTEXT_H_
#define _CONTEXT_H_
class State;
/**
*
**/
class Context{
public:
Context();
Context(State* state);
~Context();
void Handle();
void OperationForStateA();
void OperationForStateB();
protected:
private:
friend class State; //表明在 State 类中可以访问
Context 类的 private 字段,重要是访问 ChangeState
void ChangeState(State* state);
private:
State* _state;
};
#endif //~_CONTEXT_H_
#include "Context.h"
#include "State.h"
#include <iostream>
using namespace std;
Context::Context(){
}
Context::Context(State* state){
this->_state = state;
}
Context::~Context(){
delete _state;
}
void Context::Handle(){
_state->Handle(this);
}
void Context::ChangeState(State* state){
///_state->ChangeState(this,state);
this->_state = state;
}
void Context::OperationForStateA(){
cout<<"Do operation in State A ";
}
void Context::OperationForStateB(){
cout<<"Do operation in State B ";
}
#ifndef _STATE_H_
#define _STATE_H_
class Context; //前置声明
class State{
public:
State();
virtual ~State();
virtual void Handle(Context* con) = 0;
protected:
void ChangeState(Context* con,State* st);
private:
//bool ChangeState(Context* con,State* st);
};
class ConcreteStateA:public State{
public:
ConcreteStateA();
virtual ~ConcreteStateA();
void Handle(Context* con);
protected:
private:
};
class ConcreteStateB:public State{
public:
ConcreteStateB();
virtual ~ConcreteStateB();
void Handle(Context* con);
protected:
private:
};
#endif //~_STATE_H_
#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());
}
#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;
}
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
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有