Junior — Middle
Can you explain the working principle of the Observer pattern and in which scenarios it is used?
sobes.tech AI
Answer from AI
The Observer pattern implements a subscription mechanism where one object (the subject) notifies multiple other objects (observers) about changes in its state. This allows decoupling the event source from the handlers, ensuring loose coupling.
Use cases:
- Implementing event systems, for example, updating UI when data changes.
- Logging or auditing, where reactions to changes are needed without interfering with the main code.
- In plugin systems, where plugins subscribe to events.
Example in PHP:
interface Observer {
public function update($data);
}
class Subject {
private $observers = [];
private $state;
public function attach(Observer $observer) {
$this->observers[] = $observer;
}
public function setState($state) {
$this->state = $state;
$this->notify();
}
private function notify() {
foreach ($this->observers as $observer) {
$observer->update($this->state);
}
}
}
class ConcreteObserver implements Observer {
public function update($data) {
echo "State updated to: $data\n";
}
}
$subject = new Subject();
$observer = new ConcreteObserver();
$subject->attach($observer);
$subject->setState('new state');