状态模式 C++实现

来源:互联网 发布:金瓯缺 知乎 编辑:程序博客网 时间:2024/05/05 03:49
#include<iostream>#include<string>#include<cstdlib>using namespace std;/*  state 模式: 三个角色: context class / state class / concreate state class    */class work;       //前置声明 // abstract state class   class state{  public:        virtual void writeprogram(work *w) = 0;    };// context class class work    //该类 实现对state class 的修改,选择具体的 state {  private:        state * current;   //将state  class 嵌入到  context 中以便对其进行修改 。         int hour;  public:                work(state *s):current(s),hour(0)        {                   }                void setstate(state *s)        { delete current;          current = s;            }        int get_hour()        {          return hour;            }        void set_hour(int value)        {          hour = value;            }        void writeprogram()        {          current->writeprogram(this);            }                };// concreate state class class rest: public state{  public:        void writeprogram(work *w)        {          cout <<"now is"<<w->get_hour()<<"and is surposed to rest!"<< endl;            }   };class evening: public state{  public:        void writeprogram(work *w)        {          if(w->get_hour() < 20)          {            cout <<"time is "<<w->get_hour()<<"evening now !"<< endl;                }              else          {            w->setstate(new rest());              w->writeprogram();                 }        }    };class afternoon: public state{   public:        void writeprogram(work *w)        {          if(w->get_hour() < 17)          {            cout <<"time is "<<w->get_hour()<<"afternoon go on!"<< endl;                }              else          {             w->setstate(new evening());               w->writeprogram();                 }        }    };class midlenoon: public state{   public:        void writeprogram(work *w)         {          if(w->get_hour() < 14)          {            cout <<"time is "<<w->get_hour()<<" midlenoon rest time"<< endl;                }              else          {            w->setstate(new afternoon());             w->writeprogram();                 }                    }    };class forenoon: public state{  public:        void writeprogram(work *w)        {          if(w->get_hour() < 12)           {              cout <<"now time is "<<w->get_hour()<<"forenoon "<<"state is very good!"<< endl;                }               else           {             w->setstate(new midlenoon());  // 修改状态              w->writeprogram();  // 调用下一个状态的writeprogram()函数,以下同理。             }        }    };int main(){  work my_work(new forenoon());    for(int i = 0; i < 30; i = i + 1)  {    my_work.set_hour(i);    my_work.writeprogram();  }      system("pause");  return 0;    }


 

 

总结:这个模式需要继续好好理解。