dart_in_action/38_design_pattern_mvc.dart

72 lines
1.6 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
Model-View-Controller模型-视图-控制器) 模式
Model模型 - 模型代表一个存取数据的对象。它也可以带有逻辑,在数据变化时更新控制器。
View视图 - 视图代表模型包含的数据的可视化。
Controller控制器 - 控制器作用于模型和视图上。它控制数据流向模型对象,并在数据变化时更新视图。它使视图与模型分离开。
*/
main(List<String> args) {
Student student = new Student();
student.name = "Robert";
student.rollNo = "10";
//创建一个视图:把学生详细信息输出到控制台
StudentView view = new StudentView();
StudentController controller = new StudentController(student, view);
controller.updateView();
//更新模型数据
controller.setStudentName("John");
controller.updateView();
}
//////////////////////////////////////////////////////////////////
///
/// 创建模型
///
class Student {
String rollNo;
String name;
}
///
/// 创建视图
///
class StudentView {
void printStudentDetails(String studentName, String studentRollNo) {
print("Student: \nName: $studentName\n Roll No: $studentRollNo");
}
}
///
/// 创建控制器
///
class StudentController {
Student _model;
StudentView _view;
StudentController(this._model, this._view);
void setStudentName(String name) {
_model.name = name;
}
String getStudentName() {
return _model.name;
}
void setStudentRollNo(String rollNo) {
_model.rollNo = rollNo;
}
String getStudentRollNo() {
return _model.rollNo;
}
updateView() {
_view.printStudentDetails(_model.name, _model.rollNo);
}
}