scala模式设计--策略模式
·
策略模式
/**
* 策略模式:
* 1.scala 实现策略模式很简单 用函数定义策略
* 2.定义一个类接收函数
*
* @author Yyyyy
* @version 1.0
*
**/
/**
* 操作数据的环境类(收银员)
*
* @param discount
* @param originalPrice
*/
class Cashier(discount: Double => Double, originalPrice: Double) {
val discountedPrice: Double = discount(originalPrice)
}
/**
* 伴生对象
*/
object Cashier {
def apply(discount: Double => Double, price: Double): Cashier = new Cashier(discount, price)
}
object Client {
def main(args: Array[String]): Unit = {
//打折策略
val dis8 = (s: Double) => s * 0.9
val dis9 = (p: Double) => p * 0.8
//打八折
val d8 = Cashier(dis8, 100)
//打九折
val d9 = Cashier(dis9, 200)
println(d8.discountedPrice)
println(d9.discountedPrice)
}
}
执行结果
90.0
160.0
Process finished with exit code 0
更多推荐

所有评论(0)