多SWITCH-CASE结构时的C语言对象方式化解

原有代码:

#include 
int main()
{
    int n=0;
    while(1)
    {
        scanf("%d",&n);
        switch(n)
        {
        case 0:
            printf("STATE0\n");
            break;
        case 1:
            printf("STATE1\n");
            break;
        case 2:
            printf("STATE2\n");
            break;
        default:
            return 0;
        }
    }
    return 0;
}

改造方案:
#include 
#define N 3 //状态值


struct State
{
    int i;
    void (*CreateState)(struct State *s);
    void (*Show)(struct State s);
    void (*StateTrans[N])(struct State s);
};

void StateTrans0(struct State s)
{
    s.i=0;
    s.Show(s);
}

void StateTrans1(struct State s)
{
    s.i=1;
    s.Show(s);
}

void StateTrans2(struct State s)
{
    s.i=2;
    s.Show(s);
}

void Show(struct State s)
{
    printf("State-%d\n",s.i);
}

void CreateState(struct State *s)
{
    s->Show=Show;
    s->StateTrans[0]=StateTrans0;
    s->StateTrans[1]=StateTrans1;
    s->StateTrans[2]=StateTrans2;
}


enum{ST0=0,ST1,ST2}STATE;//枚举状态

int main()
{
    State s;//实例化

    //初始化
    s.CreateState=CreateState;
    s.CreateState(&s);
   
    //模拟状态调用
    while(1)
    {
        scanf("%d",&STATE);   
        if(STATE<0||STATE>2)
        {
            break;
        }
        s.StateTrans[STATE](s);
    }
   
    getchar();
    return 0;
}


你可能感兴趣的:(C/C++,语言,struct,c)