• 状态模式


    1】什么是状态模式?
    
    不同的状态,不同的行为。或者说,每个状态有着相应的行为。
    
    【2】状态模式的代码示例:
    
    代码示例:
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Work;
    class State;
    class ForenonnState;
    
    
    class State
    {
    public:
        virtual void writeProgram(Work*) = 0;
    };
    
    class Work
    {
    public:
        int hour;
        State *current;
        Work();
        void writeProgram()
        {
            current->writeProgram(this);
        }
    };
    
    class EveningState : public State
    {
    public:
        void writeProgram(Work *w)
        {
            cout << "当前时间: " << w->hour << "心情很好,在看《明朝那些事儿》,收获很大!" << endl;
        }
    };
    
    class AfternoonState : public State
    {
    public:
        void writeProgram(Work *w)
        {
            if (w->hour < 19)
            {
                cout << "当前时间: " << w->hour << "下午午睡后,工作还是精神百倍!" << endl;
            }
            else
            {
                w->current = new EveningState();
                w->writeProgram();
            }
        }
    };
    
    class ForenonnState : public State
    {
    public:
        void writeProgram(Work *w)
        {
            if (w->hour < 12)
            {
                cout << "当前时间: " << w->hour << "上午工作精神百倍!" << endl;
            }
            else
            {
                w->current = new AfternoonState();
                w->writeProgram();
            }
        }
    };
    
    Work::Work()
    {
        current = new ForenonnState();
    }
    
    int main()
    {
        Work *w = new Work();
        w->hour = 21;
        w->writeProgram();
        return 0;
    }
    //Reuslt:
    //当前时间: 21心情很好,在看《明朝那些事儿》,收获很大!

    http://www.cnblogs.com/Braveliu/p/3946826.html

  • 相关阅读:
    关于证书
    title向左_右滚动效果
    js标题滚动效果
    js小结
    javascript数组以及对象
    javascript数据类型转换
    javascript变量作用域
    sqlldr
    java 配置文件读取
    hbase 协处理器
  • 原文地址:https://www.cnblogs.com/leijiangtao/p/4534596.html
Copyright © 2020-2023  润新知