Functional equivalent of decorator pattern?

后端 未结 10 2125
悲&欢浪女
悲&欢浪女 2021-02-02 06:34

What is the functional programming equivalent of the decorator design pattern?

For example, how would you write this particular example in a functional style?

10条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 07:32

    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.

提交回复
热议问题