Junior — Middle
Can you explain what the "observer" pattern is and in what cases it is used?
sobes.tech AI
Answer from AI
The "Observer" pattern is a behavioral pattern that allows an object (the subject) to notify other objects (observers) about changes in its state.
It is used when implementing a subscription mechanism, so that when data changes, related components are automatically updated without tight coupling.
Example: In a GUI, when the data model changes, all related views (widgets) receive notifications and update.
Example in Java:
interface Observer {
void update();
}
class Subject {
private List<Observer> observers = new ArrayList<>();
private int state;
public void attach(Observer o) {
observers.add(o);
}
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
private void notifyAllObservers() {
for (Observer o : observers) {
o.update();
}
}
}
class ConcreteObserver implements Observer {
@Override
public void update() {
System.out.println("State changed, observer notified.");
}
}