Observer Pattern: Structure and Participants
+ detach(observer): void
+ notifyObservers(): void
- state: State
+ setState(s: State): void
- subject: ConcreteSubject
Subject (Interface or Abstract Class): Knows its observers and provides interface for attaching/detaching observer objects. May be an interface if no common implementation is needed, or abstract class if shared behavior exists across concrete subjects.
ConcreteSubject: Stores state of interest to observers. Sends notification to its observers when state changes. The notification typically happens in setter methods or after completing a business operation.
Observer (Interface): Defines an updating interface for objects that should be notified of changes. The update() method is the contract all observers must fulfill.
ConcreteObserver: Maintains a reference to a ConcreteSubject object. Stores state that should stay consistent with the subject's state. Implements the update() method to keep its state synchronized.
First, ConcreteSubject notifies its observers whenever a change occurs.
Second, each ConcreteObserver may query the subject for information to reconcile its state.
Third, the notification can trigger updates that cause further notifications (be careful of cycles).
attach(), detach(), and notifyObservers() logic.