Decorator pattern in Scala

装饰模式在《Design Patterns: Elements of Reusable Object-Oriented Software》的定义如下:

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

对于装饰模式的优缺点或者代码样例可以参考电子工业出版社的《Java 与模式》和清华大学出版社的《Java设计模式》

下面将重点介绍在函数式编程中如何实现装饰模式
装饰模式主要是为了扩展功能,所以在下面的代码中可以看到,为add,subtract,multiply,divide四个函数“装饰”了一层打印结果的函数,使得这些函数有了新的功能

object DecoratorPattern {
  def add(a: Int, b: Int) = a + b
  def subtract(a: Int, b: Int) = a - b
  def multiply(a: Int, b: Int) = a * b
  def divide(a: Int, b: Int) = a / b

  def makeLogger(calcFn: (Int, Int) => Int) =
    (a: Int, b: Int) => {
      val result = calcFn(a, b)
      println("Result is: " + result)
      result
    }

  val loggingAdd = makeLogger(add)
  val loggingSubtract = makeLogger(subtract)
  val loggingMultiply = makeLogger(multiply)
  val loggingDivide = makeLogger(divide)

  def main(args: Array[String]): Unit = {
    loggingAdd(2, 3)
    loggingSubtract(2, 3)
    loggingMultiply(2, 3)
    loggingDivide(6, 3)
  }
}

返回目录

你可能感兴趣的:(Decorator pattern in Scala)