Observer Pattern Flashcards
(14 cards)
Subject
The object being observed; owns the state and notifies observers when it changes.
Observer
Dependent objects that are interested in changes to the subject’s state.
Concrete Subject
Implementation of the subject interface; includes state and logic for managing observers.
Concrete Observer
Implements the observer interface and defines how it reacts to changes in the subject.
notifyObservers()
Called by the subject to update all registered observers.
update()
Called by the subject on each observer to notify them of a state change.
registerObserver(o)
Adds an observer to the subject’s list.
removeObserver(o)
Removes an observer from the subject’s list.
Observer Pattern
A behavioural design pattern where a subject (publisher) maintains a list of observers (subscribers) and notifies them automatically of any state changes.
Observer Pattern Structure
Classes:
- Subject Interface
- Concrete Subject
- Observer Interface
- Concrete Observer
Subject Interface (Observer Pattern Classes)
- Methods: registerObserver(), removeObserver(), notifyObservers()
- Maintains a list of observers.
Concrete Subject (Observer Pattern Classes)
- Stores actual state (e.g. weather data or clock time).
- Implements methods from Subject interface.
Observer Interface (Observer Pattern Classes)
Declares update() method.
Concrete Observer (Observer Pattern Classes)
- Has its own state.
- Implements update() to stay consistent with the subject.