0%

设计模式-MVC模式

Model(模型) - 模型代表一个存取数据的对象
View(视图) - 视图代表模型包含的数据的可视化
Controller(控制器) - 控制器作用于模型和视图上。它控制数据流向模型对象,并在数据变化时更新视图。它使视图与模型分离开

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//我们将创建一个作为模型的 Student 对象。StudentView 是一个把学生详细信息输出到控制台的视图类,StudentController 是负责存储数据到 Student 对象中的控制器类,并相应地更新视图 StudentView。
//Model
public class Student
{
private string rollNo;
private string name;
public string RollNo()
{
get{return rollNo;}
set{this.rollNo = value;}
}
public string Name
{
get{return name;}
set{this.name = value;}
}
}
//View
public class StudentView
{
public void PrintStudentDetails(string name, string rollNo)
{
Console.WriteLine("Student Name: {0}, Roll No: {1}", name, rollNo);
}
}
//Controller
public class StudentController
{
private Strudent model;
private StudentView view;
public StudentController(Student model, StudentView view)
{
this.model = model;
this.view = view;
}
public void SetStudentName(string name)
{
model.Name = name;
}
public void SetStudentRollNo(string rollNo)
{
model.rollNo = rollNo;
}
public void GetStudentName()
{
return model.Name;
}
public void GetStudentRollNo()
{
return model.rollNo;
}
public void UpdateView()
{
view.PrintStudentDetails(model.Name, model.RollNo);
}
}
//Client
Student model = new Student();
StudentView view = new StudentView();
StudentController controller = new StudengController(model, view);
controller.SetStudentName("Xiaoming");
controller.SetStudentRollNo("10");
controller.UpdateView();