使用状态模式解决简单的信号转换问题

来源:互联网 发布:决战武林神兵进阶数据 编辑:程序博客网 时间:2024/04/26 16:46

模式说明:允许一个对象在其内部状态改变时改变它的行为,使对象看起来似乎修改了它的类。 


模式图片:


  • Context | TLNetTraffic : 包含了不同的状态
  • State | TLState : 定义一个状态接口。
  • ConcreteState | TL {Red, Yellow, Green} : 定义了不同的状态

¨TLNetTraffic.h¨
123456789
class TLNetTraffic{private:TLState* _state;public:TLNetTraffic();void setState ( TLState* state );void Handle();};
 


¨TLNetTraffic.cpp¨
1234567891011121314
TLNetTraffic::TLNetTraffic(){_state = new TLRed(this);}void TLNetTraffic::setState ( TLState* state ){_state = state;}void TLNetTraffic::Handle (){_state->Handle();}
 



TLState.h¨
12345
class TLState{  public: virtual void Handle() = 0;};
 


...我们随意定义了 三种状态,当然可以定义的更多

¨TLRed.h¨
123456789
class TLRed: public TLState{private:TLNetTraffic* _context;public:TLRed(TLNetTraffic* context);void Handle();};
 


¨TLRed.cpp¨
1234567
TLRed::TLRed(TLNetTraffic* context): _context(context) {};void TLRed::Handle(){printf("Red Light\n");_context->setState( new TLGreen(_context) );}
 



¨TLGreen.h¨
123456789
class TLGreen: public TLState{private:TLNetTraffic* _context;public:TLGreen(TLNetTraffic* context);void Handle();};
 


¨TLGreen.cpp¨
1234567
TLGreen::TLGreen(TLNetTraffic* context): _context(context) {};void TLGreen::Handle(){printf("Green Light\n");_context->setState( new TLYellow(_context) );}
 



¨TLYellow.h¨
123456789
class TLYellow: public TLState{private:TLNetTraffic* _context;public:TLYellow(TLNetTraffic* context);void Handle();};
 


¨TLYellow.cpp¨
1234567
TLYellow::TLYellow(TLNetTraffic* context): _context(context) {};void TLYellow::Handle(){printf("Yellow Light\n");_context->setState( new TLRed(_context) );}
 



12345678910111213141516171819202122
int main (int argc, char* argv[]){TLNetTraffic netTraffic;int count = 0, i=0;int seconds;while(1){   if (i%3==0)   printf("---------\nSession %d\n---------\n", ((i+1)/3)+1 );      if (count == 0) seconds =6, count = 1;   else if (count == 1) seconds = 4, count = 2;   else if (count == 2) seconds = 5, count = 0;   sleep( (clock_t)seconds * CLOCKS_PER_SEC );   netTraffic.Handle();   i++;}return 0;}
Edit & Run


原文:

http://www.cplusplus.com/articles/zAqpX9L8/

0 0
原创粉丝点击