C++状态模式(State)

 C++
时间:

使用场景

行为随状态改变而改变的场景。

条件、分支语句的代替者。

State

  • Context.h
#ifndef __CONTEXT_H__
#define __CONTEXT_H__

class State;

class Context
{
    public:
        Context();
        Context(State* state);
        ~Context();
        void OprationInterface();
        void OperationChangState();
    protected:
    private:
        friend class State;
        bool ChangeState(State* state);
    private:
        State* _state;
};

#endif
  • Context.cpp
#include"Context.h"
#include"State.h"

Context::Context() {}
Context::Context(State* state)
{
    this->_state = state;
}
Context::~Context() 
{
    delete _state;
}
void Context::OprationInterface()
{
    _state->OperationInterface(this);
}
void Context::OperationChangState()
{
    this->_state->OperationChangeState(this);
}
bool Context::ChangeState(State* state)
{
    this->_state = state;
    return true;
}
  • main.cpp
#include<iostream>
#include"Context.h"
#include"State.h"
using namespace std;




int main(int argc, char* argv[])
{
    State* st = new ConcreteStateA();
    Context* con = new Context(st);
    con->OperationChangState();
    con->OperationChangState();
    con->OperationChangState();

    if(nullptr != con)
        delete con;

    if(nullptr != st)
        st = nullptr;
    return 0;
}

0 评论