Kotlin 沒有內建轉接器模式,所以沒有很甜的寫法
情境就跟昨天一樣,假如我有兩個會員系統
今天接到一個需求
interface Carrefour {
fun getLevel(): String
}
interface Family {
fun setAge(age: Int)
fun getAge(): Int
}
class CarrefourMember : Carrefour {
override fun getLevel(): String {
return "Gold"
}
}
age
要給初始值,這也是 Kotlin 的優點class FamilyMember : Family {
private var age: Int = -1
override fun setAge(age: Int) {
this.age = age
}
override fun getAge(): Int {
return age
}
}
class Adapter(private val family: Family) : Carrefour {
override fun getLevel(): String {
}
}
class Adapter(private val family: Family) : Carrefour {
override fun getLevel(): String {
val level = if (family.getAge() > 36) {
"Old"
} else {
"Young"
}
return level
}
}
//建立老會員
val familyOld = FamilyMember()
familyOld.setAge(40)
val carrefourOld: Carrefour = Adapter(familyOld)
val levelOld = carrefourOld.getLevel()
//建立新會員
val familyYoung = FamilyMember()
familyYoung.setAge(25)
val carrefourYoung: Carrefour = Adapter(familyYoung)
val levelYoung = carrefourYoung.getLevel()
val text = StringBuilder()
text.append("\n")
text.append("40歲會員等級:")
text.append(levelOld)
text.append("\n")
text.append("25歲會員等級:")
text.append(levelYoung)
text.append("\n")
assertEquals("測試", text)
40歲會員等級:Old
25歲會員等級:Young