Kotlin 在樣版模式也也也也也沒有語法糖,所以寫法跟 Java 類似
abstract class Member {
var name: String = ""
var money: BigDecimal = BigDecimal.ZERO
abstract fun getCompany(): String
abstract fun isGold(): Boolean
}
abstract class Member {
var name: String = ""
var money: BigDecimal = BigDecimal.ZERO
abstract fun getCompany(): String
abstract fun isGold(): Boolean
fun registerStart(): String {
val text = StringBuilder()
text.append("商店名稱:")
text.append(getCompany())
text.append(" / ")
text.append("會員姓名:")
text.append(name)
text.append("\n")
text.append("消費金額:")
text.append(money)
text.append(" / ")
text.append("是金會員:")
text.append(isGold())
text.append("\n")
return text.toString()
}
}
class CarrefourMember : Member() {
override fun getCompany(): String {
return "家樂福"
}
override fun isGold(): Boolean {
val isGold: Boolean = money > BigDecimal.valueOf(1000)
return isGold
}
}
class FamilyMarkMember : Member() {
override fun getCompany(): String {
return "全家"
}
override fun isGold(): Boolean {
val isGold: Boolean = money > BigDecimal.ONE
return isGold
}
}
class KotlinTest {
@Test
fun show() {
val text = StringBuilder()
text.append("\n")
val carrefourMember1: Member = CarrefourMember()
carrefourMember1.name = "Andy"
carrefourMember1.money = BigDecimal.ONE
text.append(carrefourMember1.registerStart())
text.append("\n")
val carrefourMember2: Member = CarrefourMember()
carrefourMember2.name = "Jack"
carrefourMember2.money = BigDecimal.valueOf(2000)
text.append(carrefourMember2.registerStart())
text.append("\n")
val familyMarkMember1: Member = FamilyMarkMember()
familyMarkMember1.name = "Mark"
familyMarkMember1.money = BigDecimal.ZERO
text.append(familyMarkMember1.registerStart())
text.append("\n")
val familyMarkMember2: Member = FamilyMarkMember()
familyMarkMember2.name = "Rich"
familyMarkMember2.money = BigDecimal.TEN
text.append(familyMarkMember2.registerStart())
text.append("\n")
assertEquals("測試", text.toString())
}
}
商店名稱:家樂福 / 會員姓名:Andy
消費金額:1 / 是金會員:false
商店名稱:家樂福 / 會員姓名:Jack
消費金額:2000 / 是金會員:true
商店名稱:全家 / 會員姓名:Mark
消費金額:0 / 是金會員:false
商店名稱:全家 / 會員姓名:Rich
消費金額:10 / 是金會員:true