MVC implemented in pure C

前端 未结 3 1856
我寻月下人不归
我寻月下人不归 2020-12-22 18:03

Does anybody know of any resources that provide a straight forward example of trying to do Model View Controller design pattern in a C context? And in particular an embedded

3条回答
  •  情深已故
    2020-12-22 18:16

    my MVC framework!

    typedef struct  
    {
        int x;
    } x_model;
    
    typedef void (*f_void_x)(x_model*);
    
    void console_display_x(x_model* x)
    {
        printf("%d\r\n",x->x);
    }
    
    typedef struct  
    {
        f_void_x display;
    } x_view;
    
    typedef struct 
    {
        x_model* model;
        x_view* view;
    } x_controller;
    
    
    void create_console_view(x_view* this)
    {
        this->display = console_display_x;
    }
    
    void controller_update_data(x_controller* this, int x)
    {
        this->model->x = x;
        this->view->display(this->model);
    }
    
    void x_controler_init(x_controller* this, x_model* model, x_view* view)
    {
        this->model = model;
        this->view = view;
    }
    
    int main(int argc, char* argv[])
    {
        x_model model;
        x_view view;
        x_controller controller;
    
        create_console_view(&view);
        x_controler_init(&controller, &model, &view);
    
        controller_update_data(&controller, 24);
    }
    

    You'd probably get a bit fancier than this though. If you had multiple views on one controller you'd want something like an observer pattern to manage the views. But with this, you have pluggable views. I'd probably be a bit more strict in reality and only let the model be changed through a function and the views 'display' function pointer also only callable through a function ( I directly call them ). This allows for various hooks (for starters, check to see if the model or the view / function pointer is null). I left out memory management as it isn't too difficult to add in, but makes things look messy.

提交回复
热议问题