关于MVC(模型-视图-控制器)是一种软件设计的模式,MVC由三个部分组成: Model View 和 Controller,其中的关系如下:

模型:
主要是为了处理数据,比如:Model可以获取数据库的数据,可以从仪表中读取仪表的数据,他受控制于Controller,当然自己有变化的时候也可以通知Controller,但是Model不能控制Controller的行为.
model.h:
#pragma once
#include "callable.h"
class Model
{
public:
std::string data() const
{
return this->m_data;
}
void set_data(const std::string& data)
{
this->m_data = data;
if(this->event != nullptr)
{
this->event->notify();
}
}
void register_data_changed_handler(Callable* controller)
{
this->event = controller;
}
private:
std::string m_data;
Callable* event{nullptr};
};
其中 Callable是Controller的基类.
callable.h
#pragma once
#include <string>
class Callable
{
public:
virtual ~ Callable(){}
virtual void notify()=0;
};
视图:
主要是用于显示Model的数据,但是View不能直接跟Model打交道,之间是必须通过Controller来调用View去显示数据。
view.h
#pragma once
#include <iostream>
#include <string>
class View
{
public:
void set_data(const std::string & value) const
{
std::cout << "display string: " << value <<std::endl;
}
};
控制器
主要是用来协调Model和View的事务关系,当Model有数据更新通知Controller, Controller会读取Model的数据,让View去显示。可以发现Controller主要是拿数据通过一定的处理让View去消费。
controller.h
#pragma once
#include "model.h"
#include "view.h"
#include "callable.h"
class Controller:public Callable
{
public:
Controller(Model& model, View& view)
{
this->set_model(model);
this->set_view(view);
}
void set_model(Model &model)
{
this->model = &model;
this->model->register_data_changed_handler(this);
}
void set_view(View &view)
{
this->view = &view;
}
void notify() override
{
auto str = this->model->data();
if(this->view != nullptr)
this->view->set_data(str);
}
private:
Model* model{nullptr};
View* view{nullptr};
};
最后的组装:
main.cpp
#include <iostream>
#include "controller.h"
int main(int argc, char *argv[])
{
Model m;
View v;
Controller c(m,v);
m.set_data("Hello world");
return 0;
}
编译运行程序,就可以看到屏幕是打印出了:
display string: Hello world
至此 MVC的模式打印Hello World,就完成了。