How to implement the Observer Design Pattern in a pure functional way?

前端 未结 4 1167
感动是毒
感动是毒 2021-02-01 04:19

Let\'s say I want to implement an event bus using a OO programming language. I could do this (pseudocode):

class EventBus

    listeners = []

    public registe         


        
4条回答
  •  孤城傲影
    2021-02-01 05:04

    If the Observer pattern is essentially about publishers and subscribers then Clojure has a couple of functions that you could use:

    • add-watch
    • remove-watch

    The add-watch function takes three arguments: a reference, a watch function key, and a watch function that is called when the reference changes state.

    Clearly, because of the changes in mutable state, this is not purely functional (as you clearly requested), but add-watcher will give you a way to react to events, if that's the effect you were seeking, like so:

    (def number-cats (ref 3))
    
    (defn updated-cat-count [k r o n]
      ;; Takes a function key, reference, old value and new value
      (println (str "Number of cats was " o))
      (println (str "Number of cats is now " n)))
    
    (add-watch number-cats :cat-count-watcher updated-cat-count)
    
    (dosync (alter number-cats inc))
    

    Output:

    Number of cats was 3
    Number of cats is now 4
    4
    

提交回复
热议问题