Swift 05 策略模式 Strategy Pattern

/*
大宏药业门市售卖阿司匹林和扑热息痛商品。
学生享有95折优惠。
老人享有85折优惠。
VIP享有7折优惠。
把计算优惠控件、和选择哪种优惠控件进行解耦。
当增加新年优惠时、只需针对优惠控件编程即可。
*/

class Store {
    var p_doPrice : Double = 0.0
	var 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.0
var p_CurrenctPrice = 0.0

store.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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值