链式函数

#include <stdio.h>

typedef struct{
    int v;
    int (*next)(void);
    int (*error)(void);
} context_t;

context_t *ctx;

int start_step();
int a_step();
int b_step();
int c_step();
int finish_step();
int error_step();

int a_step()
{
    printf("a step  ctx = %c\n",ctx->v);
    int (*run_next)(void)= ctx->next;
    ctx->v = 'a';
    ctx->next = c_step;
    return run_next();
}

int b_step()
{
    printf("b step  ctx = %c\n",ctx->v);
    if(0){
        return ctx->error();
    }
    
    int (*run_next)(void)= ctx->next;
    ctx->v = 'b';
    ctx->next = finish_step;
    return run_next();
}

int c_step()
{
    printf("c step  ctx = %c\n",ctx->v);
    int (*run_next)(void)= ctx->next;
    ctx->v = 'c';
    return run_next();
}


int error_step()
{
    printf("error ctx = %c\n",ctx->v);
    ctx->v = 'e';
    return -1;
}



int start(int data)
{
    printf("start\n");
    context_t d;
    ctx  = &d;
    d.v = data;
    ctx->next = b_step;
    ctx->error = error_step;
    a_step();
    printf("final v = %c \n",ctx->v);
    
    return 0;
}
int finish_step()
{
    printf("finish ctx = %c \n",ctx->v);
    ctx->v = 'f';
    return 0;
}

int main()
{
    start('s');        
    return 0;
}

 

posted on 2018-12-03 09:18  阮減显  阅读(169)  评论(0编辑  收藏  举报

导航