Kotlin 沒有責任鏈模式的語法糖,所以寫起來就跟 Java 類似,但是 Koltin 的防空值設計,可以讓我們少寫一些空值判斷,還是很棒的
data class ApplyRequest(
var type: String
)
abstract class Mall(var name: String) {
var superior: Mall? = null
abstract fun apply(applyRequest: ApplyRequest): String
}
class FamilyMark(name: String) : Mall(name) {
override fun apply(applyRequest: ApplyRequest): String {
val text: String
if ("超商" == applyRequest.type) {
text = "這是超商類別,執行"
} else {
text = "這不是超商類別,不執行"
superior?.apply(applyRequest)
}
return text
}
}
class Carrefour(name: String) :Mall(name) {
override fun apply(applyRequest: ApplyRequest): String {
val text: String
if ("商場" == applyRequest.type) {
text = "這是商場類別,執行"
} else {
text = "這不是商場類別,不執行"
superior?.apply(applyRequest)
}
return text
}
}
class KotlinTest {
@Test
fun show() {
val text = StringBuilder()
text.append("\n")
val familyMark: Mall = FamilyMark("全家")
val carrefour: Mall = Carrefour("家樂福")
text.append("店名:")
text.append(familyMark.name)
familyMark.superior = carrefour
text.append("\n")
val applyRequest = ApplyRequest("超商")
text.append(familyMark.apply(applyRequest))
text.append("\n")
applyRequest.type = "商場"
text.append(familyMark.apply(applyRequest))
text.append("\n")
text.append("\n")
text.append("店名:")
text.append(carrefour.name)
text.append("\n")
applyRequest.type = "超商"
text.append(carrefour.apply(applyRequest))
text.append("\n")
applyRequest.type = "商場"
text.append(carrefour.apply(applyRequest))
text.append("\n")
assertEquals("測試", text.toString())
}
}
店名:全家
這是超商類別,執行
這不是超商類別,不執行
店名:家樂福
這不是商場類別,不執行
這是商場類別,執行