策略模式-Strategy

捕获.PNG

example:

fun main(args:Array){
    var cashContext:CashContext = CashContext(CashRebate(0.5))
    var result = cashContext.getResult(100.00)
    println(result)

    cashContext = CashContext(CashReturn(300.00,100.00))
    result = cashContext.getResult(450.00)
    println(result)
}

class CashContext{
    var cashSuper:CashSuper
    constructor(cashSuper: CashSuper){
        this.cashSuper = cashSuper
    }

    fun getResult(money:Double):Double{
        return cashSuper.acceptCash(money)
    }
}

abstract class CashSuper{
    abstract fun acceptCash(money:Double):Double
}

class CashNormal : CashSuper(){
    override fun acceptCash(money:Double): Double {
        return money
    }
}

class CashRebate(private var rebate:Double) : CashSuper(){
    override fun acceptCash(money:Double): Double {
        return money * rebate
    }
}

class CashReturn(private var moneyCondition:Double,private var moneyReturn: Double) : CashSuper(){
    override fun acceptCash(money:Double): Double {
       return if(money > moneyCondition) money - moneyReturn else money
    }
}

OUTPUT:

50.0
350.0

你可能感兴趣的:(策略模式-Strategy)