橋接模式在 Kotlin 中並沒有語法糖的寫法,所以跟 Java 的寫法差不多
假如有兩個抽象類別會員和支付
abstract class Member {
abstract fun getLevel(): String
}
class Gold : Member() {
override fun getLevel(): String {
return "金會員"
}
}
class Silver : Member() {
override fun getLevel(): String {
return "銀會員"
}
}
abstract class Pay(open val member: Member) {
abstract fun getPayment(): String
}
class Cash(override val member: Member) : Pay(member) {
override fun getPayment(): String {
val text = StringBuilder()
text.append(member.getLevel())
text.append(" - ")
text.append("現金支付")
return text.toString()
}
}
class CreditCard(override val member: Member) : Pay(member) {
override fun getPayment(): String {
val text = StringBuilder()
text.append(member.getLevel())
text.append(" - ")
text.append("信用卡支付")
return text.toString()
}
}
@Test
fun show() {
val text = StringBuilder()
text.append("\n")
text.append("金會員現金測試: ")
val payCashGold: Pay = Cash(Gold())
text.append(payCashGold.getPayment())
text.append("\n")
text.append("銀會員現金測試: ")
val payCashSilver: Pay = Cash(Silver())
text.append(payCashSilver.getPayment())
text.append("\n")
text.append("金會員信用卡測試: ")
val payCreditCardGold: Pay = CreditCard(Gold())
text.append(payCreditCardGold.getPayment())
text.append("\n")
text.append("銀會員信用卡測試: ")
val payCreditCardSilver: Pay = CreditCard(Silver())
text.append(payCreditCardSilver.getPayment())
text.append("\n")
assertEquals("測試", text)
}
金會員現金測試: 金會員 - 現金支付
銀會員現金測試: 銀會員 - 現金支付
金會員信用卡測試: 金會員 - 信用卡支付
銀會員信用卡測試: 銀會員 - 信用卡支付