scala模式设计--策略模式

本文介绍了Scala编程中如何运用策略模式进行设计,通过具体的执行结果展示策略模式在代码组织和可扩展性上的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

策略模式

/**
  * 策略模式:
  * 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值