C++ 模型视图控制器设计模式代码示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3984296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:12:11  来源:igfitidea点击:

Model View Controller Design pattern Code Example

c++design-patternsoop

提问by Alok Save

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 it to practice.
Wikipedia mentions Wt - Web toolkit, CppCMS and some other standard implementations which use the pattern however I have not been familiar with these, and I was just hoping and will be really grateful If anyone can provide some sample code(hopefully C++) which implements the pattern and explains the theory of the pattern being put to practice.

我正在研究模型-视图-控制器设计模式,我从理论上理解了该模式背后的概念,但我想看看人们如何实际将其付诸实践。
维基百科提到了 Wt - Web 工具包、CppCMS 和其他一些使用该模式的标准实现,但是我并不熟悉这些,我只是希望并且将非常感激如果有人可以提供一些示例代码(希望是 C++)来实现模式并解释了将模式付诸实践的理论。

回答by robev

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.

忽略Button的实现,基本上这个程序将使用GraphGUI来显示一个按下按钮时会发生变化的图形。假设它是一个条形图,它会变得更高。

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

由于模型独立于视图(按钮),控制器处理两者之间的通信,因此遵循 MVC 模式。

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.

单击按钮时,控制器通过 onButtonClicked 函数修改模型,Button 类知道在单击时调用该函数。

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.

这样做的好处是因为模型和视图是完全独立的,每个的实现都可以彻底改变并且不会影响另一个,控制器可能只需要做一些更改。如果这种情况下的模型根据一些数据库数据计算出一些结果,那么单击按钮可能会导致这种情况发生,但按钮实现不必更改。或者,当点击发生时它不告诉控制器,也许它可以在按钮被鼠标悬停时告诉控制器。无论是什么触发了更改,都将相同的更改应用于模型。

回答by Vijay Mathew

A simple text editor could be designed based on MVC. Think of the stringclass as the model, where data is stored. We might have a class called SimpleTextViewwhich displays the text in the stringattached to it, as it is. A class called KeyboardEventHandlercan act as the controller. The controller will notify the view about new keyboard events. The view in turn modifies the model (like appending or removing text). The changes in the model is reflected on all views attached to it. For instance, there might be another view called HtmlViewattached to the stringobject manipulated from within the SimpleTextView. If the user enters valid HTML tags in the SimpleTextView, the HtmlViewwill display the formatted output - real-time.

可以基于MVC设计一个简单的文本编辑器。将string类视为存储数据的模型。我们可能有一个名为的类,它按原样SimpleTextView显示string附件中的文本。被调用的类KeyboardEventHandler可以充当控制器。控制器将通知视图有关新的键盘事件。视图反过来修改模型(如附加或删除文本)。模型中的更改反映在附加到它的所有视图上。例如,可能有另一个视图被称为HtmlView附加到stringSimpleTextView. 如果用户在 中输入有效的 HTML 标签SimpleTextViewHtmlView将显示格式化的输出 - 实时。

回答by Cheers and hth. - Alf

There are couple of complete MVC examples, plus discussion, in ch 2 of an introduction to programming in Python 3.x that I wrote (I've not completed ch 3 etc., that project's been on ice for some time -- Python community really like angry swarm of bees when discovered I'd written that Python was perhaps not suitable for very large scale development, so it became difficult to get sensible feedback). It's available in PDF format from Google Docs. I don't know how well it maps to common MVC implementations, I was mostly concerned with getting the general idea across. :-)

在我编写的 Python 3.x 编程介绍的第 2 章中,有几个完整的 MVC 示例和讨论(我还没有完成第 3 章等,该项目已经搁置了一段时间——Python 社区当我发现我写过 Python 可能不适合非常大规模的开发时,我真的很喜欢愤怒的蜜蜂群,因此很难获得合理的反馈)。它可以从Google Docs获得 PDF 格式。我不知道它如何映射到常见的 MVC 实现,我最关心的是如何理解总体思路。:-)

Cheers & hth.,

干杯 & hth.,

PS: There's a nice table of contents in the PDF file but Google Docs doesn't show it. You'd need to dl and use Foxit or Acrobat or some other PDF viewer. I think there's a separate viewable TOC at Google Docs, though, haven't checked and don't remember whether updated.

PS:PDF 文件中有一个很好的目录,但 Google Docs 没有显示。您需要 dl 并使用 Foxit 或 Acrobat 或其他一些 PDF 查看器。我认为 Google Docs 上有一个单独的可查看目录,但尚未检查,也不记得是否更新。

PPS: Forgot to mention, the MVC image processing example near the end has nice pic of Lena S?derberg! :)

PPS:忘了提,接近尾声的MVC 图像处理示例有Lena S?derberg 的漂亮照片!:)

回答by doctorlai

Code is the best approach to understand and learn Model View Controller:

代码是理解和学习模型视图控制器的最佳途径:

Here is a simple JS example (from Wiki)

这是一个简单的 JS 示例(来自Wiki

/** Model, View, Controller */
var M = {}, V = {}, C = {};

/** Model stores data */
M.data = "hello world";

/** View controls what to present */
V.render = (M) => { alert(M.data); }

/** Controller bridges View and Model */
C.handleOnload = () => { V.render(M); }

/** Controller on Windows OnLoad event */
window.onload = C.handleOnload;

Here is a detailed post in C/C++ Model-View-Controller Explained in C++

这是 C/C++ Model-View-Controller Explained in C++ 中的详细帖子

MVC

MVC