装饰模式的功能等价? [英] Functional equivalent of decorator pattern?
本文介绍了装饰模式的功能等价?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
装饰器设计模式的功能编程等同物是什么?
例如,你如何写这个特定的例子在功能风格?
解决方案
在函数式编程中,你可以将一个给定的函数包装在一个新的函数中。
为了给出一个类似于你的问题中引用的Clojure例子:
我的原始绘图函数:
(defn draw [& args]
; do some stuff
)
我的函数包装器:
添加水平滚动条
(defn add-horizontal-scrollbar [draw-fn]
(fn [& args]
(draw-horizontal-scrollbar)
args)))
;添加垂直滚动条
(defn add-vertical-scrollbar [draw-fn]
(fn [& args]
(draw-vertical-scrollbar)
args)))
;添加两个滚动条
(defn add-scrollbars [draw-fn]
(add-vertical-scrollbar(add-horizontal-scrollbar draw-fn)))
这些返回一个新函数,可以在使用原始绘图函数的任何地方使用,但也可以绘制滚动条。
What is the functional programming equivalent of the decorator design pattern?
For example, how would you write this particular example in a functional style?
解决方案In functional programming, you would wrap a given function in a new function.
To give a contrived Clojure example similar to the one quoted in your question:
My original drawing function:
(defn draw [& args] ; do some stuff )
My function wrappers:
; Add horizontal scrollbar (defn add-horizontal-scrollbar [draw-fn] (fn [& args] (draw-horizontal-scrollbar) (apply draw-fn args))) ; Add vertical scrollbar (defn add-vertical-scrollbar [draw-fn] (fn [& args] (draw-vertical-scrollbar) (apply draw-fn args))) ; Add both scrollbars (defn add-scrollbars [draw-fn] (add-vertical-scrollbar (add-horizontal-scrollbar draw-fn)))
These return a new function that can be used anywhere the original drawing function is used, but also draw the scrollbars.
这篇关于装饰模式的功能等价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文