大话设计模式的例子都是用C#写的,对于熟悉其他语言的开发者来说,看起来可能不是那么的方便。为了加深理解,我在学习策略模式的时候顺便用OC和swift把书中的例子实现了,分享出来,希望对大家能有帮助。欢迎拍砖。。。。。。
swift代码:
class CashSuper{
var money:Double = 0.0
func acceptCash(money:Double)->Double{
return money
}
}
class CashNormal: CashSuper {
override func acceptCash(money:Double) -> Double {
return money
}
}
class CashReturn: CashSuper {
override func acceptCash(money:Double) -> Double {
return money-100
}
}
class CashDerate: CashSuper {
override func acceptCash(money:Double) -> Double {
return money*0.8
}
}
class CashContext {
var cs = CashSuper.init()
func inputtype(type:String){
switch type{
case "正常收费":
let cs0 = CashNormal.init()
cs = cs0
case "返利收费":
let cs1 = CashReturn.init()
cs = cs1
case "打折收费":
let cs2 = CashDerate.init()
cs = cs2
default:
print("type error")
}
}
func getResult(money:Double)->Double{
return cs.acceptCash(money)
}
}
var context = CashContext.init()
context.inputtype("打折收费")
context.getResult(100.0)