• 大话设计模式--状态模式 State -- C++实现实例


    1.状态模式: 当一个对象的内在状态改变时,允许改变其行为,这个对象看起来就像是改变了其类。

    状态模式解决的是当控制一个对象状态转换的条件表达式过于复杂, 把状态的判断逻辑转移到表示不同状态的一系列类当中,

    可以把复杂的判断逻辑简化。

    状态模式通过把各种状态转移逻辑分布到State的子类之间,减少相互之间的依赖。

    当一个对象的行为取决于它的状态,并且它必须在运行时根据状态改变它的行为时,就可以考虑使用状态模式。

    实例::

    context.h context.cpp

    #ifndef CONTEXT_H
    #define CONTEXT_H
    
    class State;
    
    class Context
    {
    public:
        Context(State *state);
        void request();
        State *state;
    
    };
    
    #endif // CONTEXT_H
    #include "context.h"
    #include "state.h"
    
    Context::Context(State *state)
    {
        this->state = state;
    }
    
    void Context::request()
    {
    
        state->handle(this);
    }

    state.h state.cpp

    #ifndef STATE_H
    #define STATE_H
    
    class Context;
    
    class State
    {
    public:
        State();
        void virtual handle(Context *context);
    };
    
    #endif // STATE_H
    #include "state.h"
    #include "context.h"
    
    State::State()
    {
    }
    
    void State::handle(Context *context)
    {
    
    }

    statea.h statea.cpp

    #ifndef STATEA_H
    #define STATEA_H
    
    #include "state.h"
    #include "context.h"
    #include "stateb.h"
    
    class StateA : public State
    {
    public:
        StateA();
        void handle(Context *context);
    };
    
    #endif // STATEA_H
    #include "statea.h"
    #include "state.h"
    #include "context.h"
    #include "stateb.h"
    #include <stdio.h>
    
    StateA::StateA()
    {
    }
    
    void StateA::handle(Context *context)
    {
        printf("on StateA
    ");
        context->state = new StateB();
    }


    stateb.h stateb.cpp

    #ifndef STATEB_H
    #define STATEB_H
    
    #include "statea.h"
    #include "context.h"
    
    class StateB : public State
    {
    public:
        StateB();
        void handle(Context *context);
    };
    
    #endif // STATEB_H
    #include "stateb.h"
    #include "statea.h"
    #include "context.h"
    #include <stdio.h>
    
    StateB::StateB()
    {
    }
    
    void StateB::handle(Context *context)
    {
        printf("on StateB
    ");
        context->state = new StateA();
    }

    main.cpp  可以状态AB之间相互切换,而只需要一个方法request

    #include <iostream>
    #include "context.h"
    #include "statea.h"
    #include "stateb.h"
    
    using namespace std;
    
    int main()
    {
        cout << "State test!" << endl;
    
        Context *c = new Context(new StateA);
        c->request();
        c->request();
        c->request();
    
        return 0;
    }


     








     

  • 相关阅读:
    MySQL之权限管理
    CentOS7使用firewalld打开关闭防火墙与端口
    CentOS 7.2 基于Docker实现MySQL主从架构
    Centos7下安装Docker
    nginx php-fpm安装配置 CentOS编译安装php7.2
    php7的扩展库安装方法
    Android 程序打包及签名
    Message和handler传递对象
    Android AlertDialog去除黑边白边自定义布局(转)
    用MVC做支付宝手机网页支付问题
  • 原文地址:https://www.cnblogs.com/xj626852095/p/3648185.html
Copyright © 2020-2023  润新知