What is the functional programming equivalent of the decorator design pattern?
For example, how would you write this particular example in a functional style?
Definition. Decorators are wrapper functions that enhance the wrapped function. You don't change the original function behavior, instead you decorate it with new behavior, achieving extensability and composability.
A Decorator Pattern says that just "attach a flexible additional responsibilities to an object dynamically". In other words, The Decorator Pattern uses composition instead of inheritance to extend the functionality of an object at runtime. The Decorator Pattern is also known as Wrapper.
By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.
In a functional language one does not need design patterns because the language is likely so high level, you end up programming in concepts that eliminate design patterns all together. The main features of functional programming (FP) include functions as first-class values, currying, immutable values, etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With