Kotlin设计模式:MVC模式

本篇使用kotlin的MVC模式,MVC模式在简单应用时候会显得很繁琐,可以直接操作modal,却要通过控制器,但是当应用越来越大的时候,MVC将数据与视图分离,更方便后期维护。所有交互通过控制器来实现。

Modal使用kotlin的数据类。

具体如下:

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
65
66
67
68
/**
* 数据类Modal
*/
data class Student(private var name: String, private var age: Int) {

fun getName(): String = this.name
fun setName(newName: String) = { name = newName }()
fun getAge(): Int = this.age
fun setAge(newAge: Int) = { age = newAge }()
}

/**
* 视图层 View
*/
class View {

fun showView(name: String, age: Int) = println("name:$name,age:$age")
}

/**
* 控制器 Controller
*/
class Controller(private var view: View, private var modal: Student) {

fun setName(newName: String) = modal.setName(newName)
fun setAge(newAge: Int) = modal.setAge(newAge)
fun getName(): String = modal.getName()
fun getAge(): Int = modal.getAge()
fun updateView() {
println("更新视图:------------")
view.showView(modal.getName(), modal.getAge())
}

}

/**
* kotlin MVC模式
* @author IWH
* android默认的开发模式就是MVC,activity属于控制器负责XML与Modal的处理
*/
fun main() {
val view = View()
val modal = Student("iwh", 20)
val controller = Controller(view, modal)
view.showView(controller.getName(), controller.getAge())
controller.setAge(21)
controller.setName("jack")
controller.updateView()
main2()


}

/**
* 使用kotlin特性
*/
fun main2() {
View().apply outer@{
Student("iwh", 20).apply inner@{
with(Controller(this@outer, this@inner)) last@{
this@outer.showView(this.getName(), this.getAge())
setName("jack")
setAge(21)
updateView()
}
}
}
}

null

输出:

null