裝飾模式在《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.
對于裝飾模式的優(yōu)缺點(diǎn)或者代碼樣例可以參考電子工業(yè)出版社的《Java 與模式》和清華大學(xué)出版社的《Java設(shè)計(jì)模式》
下面將重點(diǎn)介紹在函數(shù)式編程中如何實(shí)現(xiàn)裝飾模式
裝飾模式主要是為了擴(kuò)展功能宝泵,所以在下面的代碼中可以看到呈野,為add玉组,subtract,multiply延柠,divide四個(gè)函數(shù)“裝飾”了一層打印結(jié)果的函數(shù),使得這些函數(shù)有了新的功能
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)
}
}