Kotlin 版的裝飾模式跟 Java 版差別在可以用by
這樣就能用委託的方式來實作
interface Fans {
fun getTitle(): String
}
by
來用委託的方式來實作abstract class Title(private val fans: Fans) : Fans by fans {
}
夥伴
data class Member(var name: String = "") : Fans {
override fun getTitle(): String {
return "夥伴"
}
}
很油
類別,用來當稱號class Oil(private val fans: Fans) : Title(fans) {
override fun getTitle(): String {
return "很油" + super.getTitle()
}
}
狂熱
類別,用來當稱號class Fire(private val fans: Fans) : Title(fans) {
override fun getTitle(): String {
return "狂熱" + super.getTitle()
}
}
val text = StringBuilder()
val member: Fans = Member()
text.append("\n")
text.append("會員加入獲得稱號: ")
text.append(member.getTitle())
text.append("\n")
val oil = Oil(member)
text.append("會員花一千獲得稱號: ")
text.append(oil.getTitle())
text.append("\n")
val fire = Fire(oil)
text.append("會員花一萬獲得稱號: ")
text.append(fire.getTitle())
text.append("\n")
assertEquals("測試", text)
會員加入獲得稱號: 夥伴
會員花一千獲得稱號: 很油夥伴
會員花一萬獲得稱號: 狂熱很油夥伴