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)")

你可能感兴趣的:(设计模式,Design,pattern)