设计模式-State(行为模式)-很好的实现了对象的状态逻辑与动作实现的分类,状态逻辑在State的派生类实现,动作可以放在Context类中实现。
以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//Context.h
#pragma once class State; class Context { public: Context(); Context(State* st); virtual ~Context(); void OperationInference(); void OperationChangeState(); protected: private: friend class State; bool changeState(State* st); State* _state; };
//Context.cpp
#include"Context.h" #include"State.h" Context::Context() {} Context::Context(State* st) { this->_state = st; } Context::~Context() { delete _state; } void Context::OperationInference() { _state->OperationInference(this); } bool Context::changeState(State* state) { this->_state = state; return true; } void Context::OperationChangeState() { _state->OperationChangemode(this); }
//State.h
#pragma once class Context; class State { public: State(); virtual ~State(); virtual void OperationInference(Context*) = 0; virtual void OperationChangemode(Context*) = 0; protected: bool changeState(Context* con, State* st); private: }; class ConcreateStateA:public State { public: ConcreateStateA(); virtual ~ConcreateStateA(); virtual void OperationInference(Context*); virtual void OperationChangemode(Context*); private: protected: }; class ConcreateStateB :public State { public: ConcreateStateB(); virtual ~ConcreateStateB(); virtual void OperationInference(Context*); virtual void OperationChangemode(Context*); private: protected: };
//State.cpp
#include"State.h" #include"context.h" #include<iostream> State::State(){} State::~State(){} void State::OperationInference(Context* con) { std::cout << "State::..." << std::endl; } bool State::changeState(Context* con, State* st) { con->changeState(st); return true; } void State::OperationChangemode(Context* con) { } ConcreateStateA::ConcreateStateA() { } ConcreateStateA::~ConcreateStateA() {} void ConcreateStateA::OperationInference(Context* con) { std::cout << "OperationInference ConcreateStateA" << std::endl; } void ConcreateStateA::OperationChangemode(Context* con) { OperationInference(con); this->changeState(con, new ConcreateStateB()); } ConcreateStateB::ConcreateStateB(){} ConcreateStateB::~ConcreateStateB(){} void ConcreateStateB::OperationInference(Context* con) { std::cout << "OperationInference ConcreateStateB" << std::endl; } void ConcreateStateB::OperationChangemode(Context* con) { OperationInference(con); this->changeState(con, new ConcreateStateA()); }
//main.cpp
#include"Context.h" #include"State.h" #include<iostream> int main(int args, char* argv) { State* st = new ConcreateStateA(); Context* con = new Context(st); con->OperationChangeState(); con->OperationChangeState(); con->OperationChangeState(); if (!con) delete con; if (NULL != st) st = NULL; return 0; }