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》

  • 相关阅读:
    yii2的安装
    php Laravel windows安装
    vimrc for windows
    Magento学习
    php Ajax 局部刷新
    php用于URL的base64
    分享自建的 Jrebel License Server 激活 Jrebel
    Windows下安装Redis服务(zip)
    Windows下安装Redis服务
    MySQL中有关TIMESTAMP和DATETIME的总结
  • 原文地址:https://www.cnblogs.com/xkxjy/p/3672247.html
Copyright © 2011-2022 走看看