Kotlin设计模式:工厂模式

本篇继续练习kotlin设计模式之工厂模式,Factory,这个模式许多第三方类库都在使用,但是对于一般简单的对象类型还是直接使用新建比较好。用工厂反而繁琐,多此一举。

上代码:很直观,就不多说了。

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
package KotlinMode

/**
* 工厂模式
*/

interface Fruits {
fun showName()
}

class Lemon(private val strType: String) : Fruits {
override fun showName() {
println("当前构建对象是:$strType")
}
}
class Pear(private val strType: String) : Fruits by Lemon(strType)
class Watermelon(private val strType: String) : Fruits by Lemon(strType)

/**
* 创建工厂
*/
class FruitsFactory {

fun createType(type: String): Fruits? {
return when (type) {
"Pear" -> {
Pear(type)
}
"Watermelon" -> {
Watermelon(type)
}
"Lemon" -> {
Lemon(type)
}
else -> null
}
}

}


fun main() {

val lemon = FruitsFactory().createType("Lemon")
lemon?.showName()
val watermelon = FruitsFactory().createType("Watermelon")
watermelon?.showName()
val pear = FruitsFactory().createType("Pear")
pear?.showName()


}

null

输出:

null