通过选择策略类,来执行不同算法分支。核心是通过注入对象,改变行为。
Jack的水果店新增加优惠卷活动,所以整个程序流程在结算的时候又多了扣去优惠,并且优惠服务是可选择的。
定义一个算法接口
interface Discount {
fun calculate(money:Int):Int
}
将三种优惠算法实现
class FullDiscount:Discount {
override fun calculate(money: Int): Int {
if (money>200){
println("优惠减免20元")
return money-20
}
return money
}
}
class NewerDiscount:Discount {
override fun calculate(money: Int): Int {
println("新顾客尊享满100减20")
if (money>100){
return money-20
}
return money
}
}
class SecondDiscount:Discount {
override fun calculate(money: Int): Int {
val balance = money*0.9
return balance.toInt()
}
}
使用策略模式注入不同的算法
abstract class ShoppingCart(open var products:List<Fruit> = ArrayList()) {
private var discount:Discount?=null
@JvmName("setDiscount1")
fun setDiscount(discount: Discount){
this.discount =discount
}
//提交订单
fun submitOrder(){
//计算商品金额
var money = balance()
money = discount!!.calculate(money)
println("需要支付的总金额为${money}元")
//保存订单
pay(money)
//送货上门
sendHome()
}
//计算金额
private fun balance():Int{
var money:Int = 0
println("商品清单:")
for (fruit in products){
Factory.pack(fruit,fruit.price)
println("${fruit.name},${fruit.price}")
money+=fruit.price
}
return money
}
private fun sendHome(){
println("三公里以内,免费送货上门")
}
//提交保存
abstract fun pay(money:Int)
}
测试
class ShoppingCartClient {
companion object{
var discounts:MutableMap<String,Discount> = mutableMapOf()
init {
discounts["full"] = FullDiscount()
discounts["newer"] = NewerDiscount()
discounts["second"] = SecondDiscount()
}
@JvmStatic
fun main(args: Array<String>) {
val banana = Banana("香蕉",40)
val apple = Apple("苹果",50)
val banana2 = Banana("黄金蕉",60)
val shopping = OnlineShopping(listOf(banana,apple,banana2))
discounts["newer"]?.let { shopping.setDiscount(it) }
shopping.submitOrder()
}
}
}
测试结果
优点
缺点