zoukankan      html  css  js  c++  java
  • State 状态模式

    常见设计模式之状态模式

    青蛙王子的故事,青蛙王子在公主亲吻前后表现是不一样的,这里以打招呼为例。

    //: C10:KissingPrincess.cpp
    #include <iostream>
    using namespace std;
    
    class Creature {
      bool isFrog;
    public:
      Creature() : isFrog(true) {}
      void greet() {
        if(isFrog)
          cout << "Ribbet!" << endl;
        else
          cout << "Darling!" << endl;
      }
      void kiss() { isFrog = false; }
    };
    
    int main() {
      Creature creature;
      creature.greet();
      creature.kiss();
      creature.greet();
    } ///:~
    


    我们发现,在greet()里进行了判断,但又很多这种函数的时候,这个判断就很烦琐了

    于是state模式上场了

    //: C10:KissingPrincess2.cpp
    // The State pattern.
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Creature {
      class State {
      public:
        virtual string response() = 0;
      };
      class Frog : public State {
      public:
        string response() { return "Ribbet!"; }
      };
      class Prince : public State {
      public:
        string response() { return "Darling!"; }
      };
      State* state;
    public:
      Creature() : state(new Frog()) {}
      void greet() {
        cout << state->response() << endl;
      }
      void kiss() {
        delete state;
        state = new Prince();
      }
    };
    
    int main() {
      Creature creature;
      creature.greet();
      creature.kiss();
      creature.greet();
    } ///:~
    


    使用了不同的实现,就不要进行判断了。

    It is not necessary to make the implementing classes nested or private, but if you can it creates cleaner code.
    Note that changes to the State classes are automatically propagated throughout your code, rather than requiring an edit across the classes in order to effect changes.


    内容源自:《TICPP-2nd-ed-Vol-two》

  • 相关阅读:
    转载——关于scanf造成死循环
    转载——关于C#延时
    2013.02.13——笔记
    最近计划
    关于毕业设计——2013.4.12
    关于c#中combobox赋值问题
    使用DWE编辑对话框窗体
    Insert New Class (a2BusNew under BusItem)
    将TCE链接加入新工作通知(NewWorkAssignment,Sig)邮件中
    创建Relation并Add到数据库
  • 原文地址:https://www.cnblogs.com/xkxjy/p/3672247.html
Copyright © 2011-2022 走看看