我正在研究模型- View - Controller 设计模式,我从理论上理解该模式背后的概念,但我想看看实际如何将其付诸实践。
维基百科提到了 Wt - Web 工具包、CppCMS 和其他一些使用该模式的标准实现,但是我并不熟悉这些,我只是希望和
如果有人可以提供一些示例代码(希望是 C++)来实现该模式并解释将模式付诸实践的理论,将不胜感激。
最佳答案
这是我做的一个简单示例(没有尝试编译它,如果有错误请告诉我):
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;
};
忽略 Button 的实现,基本上这个程序将使用 GraphGUI 来显示一个图形,该图形会在按下按钮时发生变化。假设它是一个条形图,它会变高。
由于模型独立于 View (按钮), Controller 处理两者之间的通信,因此遵循 MVC 模式。
单击按钮时, Controller 通过 onButtonClicked 函数修改模型,Button 类知道在单击时调用该函数。
这样做的美妙之处在于模型和 View 是完全独立的,每个的实现都可以彻底改变并且不会影响另一个, Controller 可能只需要做一些改变。如果本例中的模型根据一些数据库数据计算出一些结果,那么单击按钮可能会导致这种情况发生,但按钮实现不必更改。或者,不是在点击发生时告诉 Controller ,也许它可以在鼠标悬停在按钮上时告诉 Controller 。无论是什么触发了更改,相同的更改都会应用于模型。
关于c++ - Model View Controller 设计模式代码示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3984296/