Model View Controller Design pattern Code Example

后端 未结 4 430
北恋
北恋 2021-02-01 09:35

I was studying the Model-View-Controller design pattern and i understand the concept behind the pattern theorotically, but I wanted to get a peek at how one would actually put i

4条回答
  •  一向
    一向 (楼主)
    2021-02-01 10:22

    Here's a quick example I made (didn't try compiling it, let me know if there's errors):

    class Button; // Prewritten GUI element
    
    class GraphGUI {
    public:
        GraphGUI() {
            _button = new Button("Click Me");
            _model = new GraphData();
            _controller = new GraphController(_model, _button);
        }
        ~GraphGUI() {
            delete _button;
            delete _model;
            delete _controller;
        }
    
        drawGraph() {
            // Use model's data to draw the graph somehow
        }
        ...
    
    private:
        Button*              _button;
        GraphData*           _model;
        GraphController*     _controller;
    };
    
    class GraphData {
    public:
        GraphData() {
            _number = 10; 
        }
        void increaseNumber() {
            _number += 10;
        }
        const int getNumber() { return _number; }
    private:
        int _number;
    };
    
    class GraphController {
    public:
        GraphController(GraphData* model, Button* button) {
            __model = model;
            __button = button;
            __button->setClickHandler(this, &onButtonClicked);
        }
    
        void onButtonClicked() {
            __model->increaseNumber();
        }
    
    private:
        // Don't handle memory
        GraphData*    __model;
        Button*       __button; 
    };
    

    Ignoring the implementation of Button, basically this program will use GraphGUI to display a graph that will change when a button is pressed. Let's say it's a bar graph and it will get taller.

    Since the model is independent of the view (the button), and the controller handles the communication between the two, this follows the MVC pattern.

    When the button is clicked, the controller modifies the model via the onButtonClicked function, which the Button class knows to call when it is clicked.

    The beauty of this is since the model and view are completely independent, the implementation of each can drastically change and it won't affect the other, the controller might simply have to make a few changes. If the model in this case calculated some result based off some database data, then clicking the button could cause this to happen, but the button implementation wouldn't have to change. Or, instead of telling the controller when a click occurs, maybe it can tell the controller when the button is moused-over. The same changes are applied to model, regardless of what triggered the changes.

提交回复
热议问题