MVC 模式

时间:2022-07-17 16:34:19

1.MVC 模式简介

MVC 模式代表 Model-View-Controller(模型-视图-控制器) 模式。这种模式用于应用程序的分层开发。
Model(模型):模型代表一个存取数据的对象或 JAVA POJO。它也可以带有逻辑,在数据变化时更新控制器。
View(视图):视图代表模型包含的数据的可视化。
Controller(控制器) :控制器作用于模型和视图上。它控制数据流向模型对象,并在数据变化时更新视图。它使视图与模型分离开。

2.示例Demo

class Student {
private String name;
private String number; public void setName(String name) {
this.name = name;
} public String getName() {
return name;
} public void setNumber(String number) {
this.number = number;
} public String getNumber() {
return number;
}
} class StudentView {
public void updateView(Student student) {
System.out.println("Student:");
System.out.println("Name: " + student.getName());
System.out.println("Number: " + student.getNumber());
}
} class StudentControler {
private Student model;
private StudentView view;
public StudentControler(Student model, StudentView view) {
this.model = model;
this.view = view;
} public void setStudentName(String name) {
model.setName(name);
} public String getStudentName() {
return model.getName();
} public void setStudentNumber(String number) {
model.setNumber(number);
} public String getStudentNumber() {
return model.getNumber();
} public void updateView() {
view.updateView(model);
} } public class MVCPatternDemo {
public static void main(String args[]) {
Student model = new Student();
model.setName("ZhangShan");
model.setNumber("123456789");
StudentView view = new StudentView();
StudentControler control = new StudentControler(model, view);
control.updateView();
}
}

参考:http://www.runoob.com/design-pattern/mvc-pattern.html