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

时间:2021-01-21 22:00:34
【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】

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

typedef struct _State
{
void (*process)();
struct _State* (*change_state)();

}State;
   说明一下,这里定义了两个变量,分别process函数和change_state函数。其中proces函数就是普通的数据操作,
void normal_process()
{
printf("normal process!\n");
}

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

struct _State* change_state()
{
State* pNextState = NULL;

pNextState = (struct _State*)malloc(sizeof(struct _State));
assert(NULL != pNextState);

pNextState ->process = next_process;
pNextState ->change_state = next_change_state;
return pNextState;
}

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

typedef struct _Context
{
State* pState;
void (*change)(struct _Context* pContext);

}Context;

void context_change(struct _Context* pContext)
{
State* pPre;
assert(NULL != pContext);

pPre = pContext->pState;
pContext->pState = pPre->changeState();
free(pPre);
return;
}