设计模式26 - MVC 模式

作者:billy
版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处

MVC 模式

MVC 模式代表 Model-View-Controller(模型-视图-控制器) 模式。这种模式用于应用程序的分层开发

  • Model(模型) - 模型代表一个存取数据的对象。它也可以带有逻辑,在数据变化时更新控制器。
  • View(视图) - 视图代表模型包含的数据的可视化。
  • Controller(控制器) - 控制器作用于模型和视图上。它控制数据流向模型对象,并在数据变化时更新视图。它使视图与模型分离开。
    在这里插入图片描述

使用场景

  • Web开发领域。
  • 移动互联开发。
  • 与交互相关的开发,关注资源的调用和响应,注重系统的稳定性和可扩展性的较大型项目。

优缺点

  • 优点:
    1、耦合性低。
    2、重用性高。
    3、生命周期成本低。
    4、部署快。
    5、可维护性高。
    6、有利软件工程化管理。

  • 缺点:
    1、没有明确的定义。
    2、不适合小型,中等规模的应用程序。
    3、增加系统结构和实现的复杂性。
    4、视图与控制器间的过于紧密的连接。
    5、视图对模型数据的低效率访问。
    6、一般高级的界面工具或构造器不支持此模式。

注意事项

所有关于数据库的操作都在模型里面做,不涉及到数据库的在控制器中完成

UML结构图

在这里插入图片描述

代码实现

student.h
创建类 Student,可获取姓名和编号,作为模型Model

#include <string>
using namespace std;

class Student
{
public:
    string getName() { return name; }
    string getRollNo() { return rollNo; }

    void setName(string name) { this->name = name; }
    void setRollNo(string rollNo) { this->rollNo = rollNo; }

private:
    string name;
    string rollNo;
};

studentview.h
创建类 StudentView,可输出学生信息,作为视图View

#include <string>
#include <iostream>
using namespace std;

class StudentView
{
public:
    void printStudentDetails(string studentName, string studentRollNo)
    {
        cout << "Student: ";
        cout << "Name: " + studentName;
        cout << ", Roll No: " + studentRollNo << endl;
    }
};

studentcontroller.h
创建类 StudentController,可修改model数据,更新view

#include "student.h"
#include "studentview.h"

class StudentController
{
public:
    StudentController(Student model, StudentView view)
    {
        this->model = model;
        this->view = view;
    }

    void setStudentName(string name)
    {
        model.setName(name);
    }

    string getStudentName()
    {
        return model.getName();
    }

    void setStudentRollNo(string rollNo)
    {
        model.setRollNo(rollNo);
    }

    string getStudentRollNo()
    {
        return model.getRollNo();
    }

    void updateView()
    {
        view.printStudentDetails(model.getName(), model.getRollNo());
    }

private:
    Student model;
    StudentView view;
};

main.cpp
实例应用 - 通过control修改数据后,更新view显示

#include "studentcontroller.h"

int main()
{
    Student *model = new Student();
    model->setName("Billy");
    model->setRollNo("18");

    StudentView *view = new StudentView();

    StudentController *controller = new StudentController(*model, *view);

    controller->updateView();
    controller->setStudentName("John");

    controller->updateView();

    return 0;
}

运行结果:
Student: Name: Billy, Roll No: 18
Student: Name: John, Roll No: 18
发布了61 篇原创文章 · 获赞 218 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_34139994/article/details/96590136