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

前端 未结 4 1172
感动是毒
感动是毒 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:13

    More over, since the listeners collection changes over time, it would not be possible to create a pure functional solution, right?

    This is less of a problem - in general, whenever you'd modify an object's attribute in an imperative solution, you can compute a new object with the new value in a pure functional solution. I believe that the actual event propagation is a bit more problematic - it would have to be implemented by a function that takes the event, the whole set of potential observers plus the EventBus, then filters out the actual observers and returns a whole new set of objects with the new states of observers computed by their event processing functions. Non-observers would of course be the same in the input and output sets.

    It gets interesting if those observers generate new events in response to their on methods (here: functions) being called - in this case you need to apply the function recursively (perhaps allowing it to take more than one event) until it produces no more events to process.

    In general, the function would take an event and a set of objects and return the new set of objects with new states representing all modifications resulting from the event propagation.

    TL;DR: I think that modeling event propagation in a pure functional way is complicated.

提交回复
热议问题