state模式

编译都没过,发生点事,心有点乱

随便看看就好

state.h

#ifndef _STATE_H

#define _STATE_H

#include

using namespace std;

class Context

{

public:

Context() {

}

Context(State* state) : _state(state) {

}

~Context() {

}

void OperationInterface() {

_state->OperationInterface(this);

}

void OperationChangeState() {

_state->OperationChangeState(this);

}

private:

friend class State;

bool ChangeState(State* state) {

_state = state;

return true;

}

private:

State* _state;

};

class State

{

public:

State() {

}

virtual ~State() {

}

virtual void OperationInterface(Context *)=0;

virtual void OperationChangeState(Context *)=0;

protected:

bool ChangeState(Context* con,State* st) {

con->ChangeState(st);

return true;

}

};

class ConcreteStateA : public State

{

public:

ConcreteStateA() {

}

virtual ~ConcreteStateA() {

}

virtual void OperationInterface(Context*) {

cout << "ConcreteStateA:OperationInterface" << endl;

}

virtual void OperationChangeState(Context* con) {

OperationInterface(con);

ChangeState(con, new ConcreteStateB());

}

};

class ConcreteStateB : public State

{

public:

ConcreteStateB() {

}

virtual ~ConcreteStateB() {

}

virtual void OperationInterface(Context*) {

cout << "ConcreteStateB:OperationInterface" << endl;

}

virtual void OperationChangeState(Context* con) {

OperationInterface(con);

ChangeState(con, new ConcreteStateA());

}

};

#endif // _STATE_H

state.cpp

#include "state.h"

int main()

{

State* st = new ConcreteStateA();

Context* con = new Context(st);

con->OperationInterface();

con->OperationInterface();

con->OperationInterface();

return 0;

}

你可能感兴趣的:(state模式)