Here is a long answer explaining the Observer design pattern:
The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. It is used where changes in one object need to be propagated to other objects and it allows loose coupling between objects.
In this pattern, there are two main roles - the Subject and the Observer. The Subject is the object that can be observed and it maintains a list of observers. The Observer is the object that observes the Subject. It is interested in the state of the Subject and receives notifications from the Subject on state changes.
When the Subject's state changes, it notifies all observers by calling their update() method. Observers can then query the Subject's state to ensure they have the correct updated information. This keeps the Subject and Observer decoupled - the Subject does not need to know the concrete class of the Observer or how it will use the updated information. New observers can be added or removed dynamically.
Some key advantages of the Observer pattern are:
-
It promotes loose coupling between objects. The Subject and Observer are decoupled - they only know about each other through their abstract interfaces.
-
It supports open/closed principle as new types of observers can be added without modifying existing observers and subjects.
-
It simplifies object relationships as the dependencies between objects are defined in a clear one-way direction (Subject to Observer).
-
It encourages reusable object-oriented code as the update interface can be called by any observer making the same request.
The basic workflow is:
- Subject maintains a list of observers.
- Observer expresses interest in Subject by subscribing to it.
- When Subject's state changes, it notifies all observers.
- Observer updates itself based on the event.
Here is an example implementation of the Observer pattern in Java:
// Subject interface
interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}
// Concrete Subject
class TemperatureSensor implements Subject {
private List<Observer> observers;
private float temperature;
public TemperatureSensor() {
observers = new ArrayList<>();
}
public void setTemperature(float temp) {
temperature = temp;
notifyObservers();
}
public void registerObserver(Observer o) {
observers.add(o);
}
public void removeObserver(Observer o) {
observers.remove(o);
}
public void notifyObservers() {
for(Observer observer : observers) {
observer.update();
}
}
}
// Observer interface
interface Observer {
void update();
}
// Concrete Observer
class LCDDisplay implements Observer {
public void update() {
// get new temperature from sensor and display it
}
}
In summary, the Observer pattern encapsulates the core decoupling between dependent and independent objects, making it very useful for creating loosely coupled and reusable code.