DesignPattern/21.StatePattern/2.Code/Demo.h

77 lines
1.1 KiB
C
Raw Permalink Normal View History

2019-11-09 02:41:43 +00:00
#ifndef __DEMO_H__
#define __DEMO_H__
// <20><><EFBFBD><EFBFBD>״̬<D7B4><CCAC>
class State
{
public:
virtual ~State(){}
2019-11-09 02:41:43 +00:00
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>󷽷<EFBFBD>
virtual void handle() = 0;
};
// <20><><EFBFBD><EFBFBD>״̬<D7B4><CCAC>
class ConcreteState :public State
{
public:
// ʵ<><CAB5>
void handle(){
// <20><><EFBFBD><EFBFBD>
}
};
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class Context
{
public:
// set<65><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>״̬<D7B4><CCAC><EFBFBD><EFBFBD>
void setState(State* iState){
this->state = iState;
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>װ<EFBFBD>ķ<EFBFBD><C4B7><EFBFBD>
void request(){
// do something
state->handle();
}
private:
// <20><><EFBFBD><EFBFBD>״̬<D7B4><CCAC><EFBFBD><EFBFBD>
State *state;
};
// 1.<2E>ɻ<EFBFBD><C9BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʵ<EFBFBD><CAB5><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>״̬<D7B4><CCAC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class Context
{
public:
void convertState(){
if (condition1){
this->state = new ConcreteStateA();
}
else if (condition2){
this->state = new ConcreteStateB();
}
else{
// do something
}
}
private:
// <20><><EFBFBD><EFBFBD>״̬<D7B4><CCAC><EFBFBD><EFBFBD>
State *state;
};
// 2.<2E>о<EFBFBD><D0BE><EFBFBD>״̬<D7B4><CCAC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ת<EFBFBD><D7AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>״̬<D7B4><CCAC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class ConcreteState :public State
{
public:
void convertState(Context* ctx){
if (condition1){
ctx->setState(new ConcreteStateA());
}
else if (condition2){
ctx->setState(new ConcreteStateB());
}
else{
// do something
}
}
};
#endif //__DEMO_H__