现在的位置: 首页 > 综合 > 正文

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

2012年12月01日 ⁄ 综合 ⁄ 共 1504字 ⁄ 字号 评论关闭

【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】

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

 

  1. typdef struct _State  
  2. {  
  3.     void (*process)();  
  4.     struct _Sate* (*change_state)();  
  5.   
  6. }State;  

   说明一下,这里定义了两个变量,分别process函数和change_state函数。其中proces函数就是普通的数据操作,

  1. void normal_process()  
  2. {  
  3.     printf("normal process!\n");  
  4. }    

 

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

 

  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变换函数。

 

  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. }  

抱歉!评论已关闭.