In the original version, this pattern allows several observers to receive messages about a change in the state of a single object. Is it possible to do something similar, but to make it the other way around: one observer receives messages about the state change of several objects? Moreover, the observer must respond to messages from different objects in different ways. I have one idea about this. In the message processing method, pass a parameter indicating which event caused it, and on this basis call handlers. Is it possible to make it more beautiful?

  • Can. If Java is available through a very good book: Freeman Er., Freeman Al., Sierra K., Bates B. - Design Patterns - 2011 - Viacheslav
  • one
    What is the difference - java or not In many explanatory books on UOP for examples it is used java =) - Zowie
  • and why you do not want to make for each object was its own set of observers? - _perchuk
  • And what else can you think of? Either one method for all observed objects with parameter processing, or one special method for each object. - skegg

4 answers 4

I would make it more banal: each object has its own event (specific to this object), and the observer just subscribes to all the necessary object events and reacts in the right way to each one in different ways (each event has its own handler). After that, you don’t need to transfer anything to anybody, make branches, additional “enumerations” and “switches”.

    each object can be an observer and notify other objects. As mentioned above, you can read in the book. It is well painted.

    • Read this book. There the situation is described “one object - many observers”, and I need the opposite, “many objects - one observer”, and for each object there is a handler. - fori1ton

    For example, in C # for this, I get a special class:

    public sealed class MutableData<T> { private T value; public MutableData() { value = default(T); } public MutableData(T value) { this.value = value; } public event EventHandler DataChanged; public T get() { return this.value; } public void set(T newValue, object sender) { value = newValue; if (DataChanged != null) { DataChanged(sender, EventArgs.Empty); } } } 

    After that, any object can be wrapped and subscribed to changes in its values ​​(of course, if they are produced through the set method).

      Try looking towards AOP (aspect-oriented programming), its philosophy is close to what you need.