Observer Pattern

The Observer pattern refers to behavioral patterns of design.
The pattern allows you to send an object state change to subscribers using a common interface.
Suppose we are developing a messenger for programmers, we have a chat screen in the application. When you receive a message with the text “problem” and “error” or “something is wrong”, you need to paint the error list screen and the settings screen in red.
Next, I will describe 2 options for solving the problem, the first is simple but extremely difficult to support, and the second is much more stable in support, but it requires skills! during initial implementation.

Common Bus

All implementations of the pattern contain sending messages when data changes, subscribing to messages, and further processing in methods. The shared bus option contains a single object (a singleton is usually used) that provides message dispatch to recipients.
Ease of implementation is as follows:

  1. The object sends an abstract message to the shared bus
  2. Another object subscribed to the shared bus catches the message and decides to process it or not.

One of the implementation options available from Apple (NSNotificationCenter subsystem), message header matching is added to the name of the method that is called by the recipient upon delivery.
The biggest drawback of this approach is that with a further change in the message, you will first need to remember and then manually edit all the places where it is processed, sent. There is a case of quick initial implementation, further long, complex support, requiring a knowledge base for correct operation.

Multicast Delegate

In this implementation, we will make the final class of the multicast delegate, as well as in the case with the common bus, objects can be subscribed to receive “messages” or “events”, however, the tasks of parsing and filtering messages are not assigned to the shoulders of objects. Instead, subscriber classes should implement the delegate’s multicast methods by which it notifies them.
This is realized by using the interfaces / protocols of the delegate, when changing the general interface, the application will stop compiling, at this point it will be necessary to change all the places of processing this message, without having to keep a separate knowledge base for remembering these places. Compiler is your friend.
In this approach, the team’s productivity is increased, since there is no need to write, store documentation, there is no need for a new developer to try to understand how a message is processed, its arguments, instead it works with a convenient and intuitive interface, so the documentation paradigm is implemented through code.
The multicast delegate itself is based on the delegate pattern, which I will write about in the next note.

References

https://refactoring.guru/design-patterns/observer