狀態模式 C++實現

#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;    
}


 

 

總結:這個模式需要繼續好好理解。

發佈了53 篇原創文章 · 獲贊 5 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章