The Observer Pattern is a design pattern that establishes a one-to-many relationship between objects, where multiple dependents (observers) are notified automatically when there is a change in the state of a subject.
In software development, it is often necessary to allow certain objects or components to stay updated with the changes in another object or component. The Observer Pattern enables this by creating a loosely coupled relationship between the subject (publisher) and the observers (subscribers) through a set of well-defined interfaces.
The key components of the Observer Pattern are:
update()
) that gets called by the subject when a change occurs.The Observer Pattern offers several benefits, including:
To implement the Observer Pattern, one can follow these steps:
update()
that passes the subject's state as a parameter.attach(observer)
, detach(observer)
, and notify()
.update()
method to handle the updates received from the subject.attach()
method. Now, any changes in the subject's state will automatically reflect on the subscribers.Let's consider a stock market application where multiple investors want to be notified whenever the price of a particular stock they are interested in changes. In this scenario, the Observer Pattern can be applied as follows:
Stock
class represents a particular stock and its state, including the price. It maintains a list of observers (investors) and provides methods to manage the list (e.g., attach(observer)
, detach(observer)
, notify()
).Investor
interface defines a method update(stock)
that notifies the investor when the price of the observed stock changes.Stock
class implements the subject interface and updates the price of the stock. When the price changes, it notifies all attached observers (investors) by calling their update(stock)
method.IndividualInvestor
, InstitutionalInvestor
, and other classes implement the observer interface. They register themselves with the subject (stock) and provide the logic in their update(stock)
method to handle the price change event. Each observer can decide how to react to the change, such as buying or selling stocks.The Observer Pattern provides a powerful mechanism to define a one-to-many dependency between objects, ensuring loose coupling and real-time updates. By implementing the observer interface, subjects and observers can communicate seamlessly without being tightly coupled. This pattern finds applications in various scenarios, such as event-driven architectures, graphical user interfaces, and real-time systems.
noob to master © copyleft