Swift 05 策略模式 Strategy Pattern

来源:互联网 发布:sql图标 编辑:程序博客网 时间:2024/06/14 13:53
/*大宏药业门市售卖阿司匹林和扑热息痛商品。学生享有95折优惠。老人享有85折优惠。VIP享有7折优惠。把计算优惠控件、和选择哪种优惠控件进行解耦。当增加新年优惠时、只需针对优惠控件编程即可。*/class Store {    var p_doPrice : Double = 0.0var discount = Discount()func setPrice (p_doIntputPrice : Double) {    p_doPrice = p_doIntputPrice}func setDiscount (p_obDiscount : Discount) {    discount = p_obDiscount}func getPrice() -> Double {    return discount.calculate(p_doIntputCalPrice : p_doPrice)}}class Discount  {func calculate(p_doIntputCalPrice : Double) -> Double {     return p_doIntputCalPrice}}class StudentDiscount : Discount {override func calculate(p_doIntputCalPrice : Double) -> Double {print("Student discount:")return p_doIntputCalPrice * 0.95}}class OlderDiscount : Discount {override func calculate(p_doIntputCalPrice : Double) -> Double {print("Older discount:")return p_doIntputCalPrice * 0.85}}class VipDiscount : Discount {override func calculate(p_doIntputCalPrice : Double) -> Double {print("Older discount:")return p_doIntputCalPrice * 0.70}}var store = Store()var p_doOriginalPrice = 60.0var p_CurrenctPrice = 0.0store.setPrice(p_doIntputPrice : p_doOriginalPrice)print("Original price is : \(p_doOriginalPrice)")var discount = Discount()// discount = StudentDiscount()// discount = OlderDiscount()discount = VipDiscount()store.setDiscount(p_obDiscount : discount)p_CurrenctPrice = store.getPrice()print("Discount price is: \(p_CurrenctPrice)")

0 0
原创粉丝点击