03.C语言和设计模式(状态模式)

来源:互联网 发布:手机电影网站源码 编辑:程序博客网 时间:2024/05/16 07:01

原文地址:http://blog.csdn.net/feixiaoxing/article/details/7185764


 状态模式是协议交互中使用得比较多的模式。比如说,在不同的协议中,都会存在启动、保持、中止等基本状态。那么怎么灵活地转变这些状态就是我们需要考虑的事情。假设现在有一个state,

[cpp] view plaincopy
  1. typedef struct _State  
  2. {  
  3.     void (*process)();  
  4.     struct _State* (*change_state)();  
  5.   
  6. }State;  
   说明一下,这里定义了两个变量,分别process函数和change_state函数。其中proces函数就是普通的数据操作,
[cpp] view plaincopy
  1. void normal_process()  
  2. {  
  3.     printf("normal process!\n");  
  4. }    

  change_state函数本质上就是确定下一个状态是什么。

[cpp] view plaincopy
  1. struct _State* change_state()  
  2. {  
  3.     State* pNextState = NULL;  
  4.   
  5.     pNextState = (struct _State*)malloc(sizeof(struct _State));  
  6.     assert(NULL != pNextState);  
  7.   
  8.     pNextState ->process = next_process;  
  9.     pNextState ->change_state = next_change_state;  
  10.     return pNextState;  
  11. }  

   所以,在context中,应该有一个state变量,还应该有一个state变换函数。

[cpp] view plaincopy
  1. typedef struct _Context  
  2. {  
  3.     State* pState;  
  4.     void (*change)(struct _Context* pContext);  
  5.       
  6. }Context;  
  7.   
  8. void context_change(struct _Context* pContext)  
  9. {  
  10.     State* pPre;  
  11.     assert(NULL != pContext);  
  12.   
  13.     pPre = pContext->pState;  
  14.     pContext->pState = pPre->changeState();  
  15.     free(pPre);  
  16.     return;     
  17. }  

0 0