您的位置:首页 > 编程语言 > Java开发

Kotlin 设计模式-工厂

2017-07-16 10:35 411 查看

Kotlin 设计模式-工厂

前言

Java有很多成熟的设计模式,当然Kotlin是JVM语言,自然对Java原始的设计模式当然可以照搬过来使用,但是毕竟是有大量的语法糖可以使用,所以Kotlin在某些设计模式使用时可以简化代码。

Kotlin工厂模式

Java中简单工厂模式使用if判断或使用 switch case 表达式 进行对象创建分发,在Kotlin则可以使用新增的 when 表达式 来增强Java中工厂模式的一些限制,比如大量的 if else判断,switch case 只能使用数字(1.6及以前)和字符串(1.7及以后增强)。

Kotlin when 表达式

kotlin when 表达式 官方说明

http://kotlinlang.org/docs/reference/control-flow.html#when-expression

when 表达式取代了类C语言中的switch 操作符。

sample

when (x) {

1 -> print("x == 1")

2 -> print("x == 2")

else -> { // Note the block

print("x is neither 1 nor 2")

}

}


主要增强的内容有以下几点

如果有分支可以用同样的方式处理的话,分支条件可以连在一起:

when (x) {
0,1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}


可以用任意表达式作为分支的条件(不必非得是常量)

when (x) {
parseInt(s) -> print("s encode x")
else -> print("s does not encode x")
}


也可以使用in 或 !in检查参数值是否在集合中

when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}


也可以用 is 或者 !is 来判断值是否是某个类型。注意,由于智能转换,你可以不用额外的检查就可以使用相应的属性或方法。

val hasPrefix = when (x) {
is String -> x.startsWith("prefix")
else -> false
}


when 也可以用来代替 if-else if 。如果没有任何参数提供,那么分支的条件就是简单的布尔表达式,当条件为真时执行相应的分支

when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}


Show me a code

interface People {
val color: String
}

class Asian(override val color: String = "Yellow") : People
class Euro (override val color: String = "White") : People

enum class Country {
Chinese, American, UK, Japanese
}

class PeopleFactory {
fun peopleForCountry(country: Country): People? {
when (country) {
Country.American, Country.UK -> return Euro()
Country.Chinese, Country.Japanese -> return Asian()
else                          -> return null
}
}
}


调用代码如下

val noCurrencyCode = "No Prople color Available"

val yellowProple = PeopleFactory().peopleForCountry(Country.Chinese)?.color() ?: noCurrencyCode
println("yellowProple color: $yellowProple")

val whiteProple = PeopleFactory().peopleForCountry(Country.American)?.color() ?: noCurrencyCode
println("whiteProple color: $whiteProple")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息