Functional equivalent of decorator pattern?

后端 未结 10 2132
悲&欢浪女
悲&欢浪女 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:15

    You can "decorate" functions by wrapping them inside other functions, typically using some form of higher order function to perform the wrapping.

    Simple example in Clojure:

    ; define a collection with some missing (nil) values
    (def nums [1 2 3 4 nil 6 7 nil 9])
    
    ; helper higher order function to "wrap" an existing function with an alternative implementation to be used when a certain predicate matches the value
    (defn wrap-alternate-handler [pred alternate-f f]
      (fn [x] 
        (if (pred x) 
          (alternate-f x)
          (f x))))
    
    ; create a "decorated" increment function that handles nils differently
    (def wrapped-inc 
      (wrap-alternate-handler nil? (constantly "Nil found!") inc))
    
    (map wrapped-inc nums)
    => (2 3 4 5 "Nil found!" 7 8 "Nil found!" 10)
    

    This technique is used extensively in functional libraries. A good example is wrapping web request handlers using Ring middleware - the linked example wraps parameter handling for html request around any existing handler.

提交回复
热议问题