The observer pattern is a software design pattern in which an object, the subject,keeps a list of its dependents, called observers, notifying them automatically of any state changes, usually by calling one of their methods.
It is mainly used for implementing distributed event handling systems, in "event driven" software, where the subject is usually named a "stream of events" or "stream source of events", while the observers are the "sinks of events". This pattern then perfectly suits any process where data arrives from some input that is not available to the CPU at startup, but instead arrives "at random" (HTTP requests, GPIO data, user input from keyboard/mouse/..., distributed databases and blockchains, ...). While not mandatory, most 'observers' implementations would use background threads listening for subject-events and other support mechanisms provided by the kernel (Linux epoll, ...).Overview
The Observer design pattern is a behavioural pattern, among the twenty-three well-known "Gang of Four" design patterns describing how to solve recurring design challenges in order to design flexible and reusable object-oriented software, i.e. objects which are easier to implement, change, test, and reuse.
Which problems can the Observer design pattern solve?
The Observer pattern addresses the following problems:
A one-to-many dependency between objects should be defined without making the objects tightly coupled.
It should be ensured that when one object changes state, an open-ended number of dependent objects are updated automatically.
It should be possible that one object can notify an open-ended number of other objects.
Defining a one-to-many dependency between objects by defining one object (subject) that updates the state of dependent objects directly is inflexible because it couples the subject to particular dependent objects. Still, it can make sense from a performance point of view or if the object implementation is tightly coupled. Tightly coupled objects can be hard to implement in some scenarios, and hard to reuse because they refer to and know about (and how to update) many different objects with different interfaces. In other scenarios, tightly coupled objects can be a better option since the compiler will be able to detect errors at compile-time and optimize the code at the CPU instruction level.
No comments:
Post a Comment