- the Observer pattern provides a blueprint for one variety of inter-class communication
- in Observer, changes in one object's state are broadcast to other objects
- the object that broadcasts is the "subject"
- the objects that receive broadcasts are the "observers"
- many observers may observe the same subject
- from GoF: 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."
- e.g., a WeatherData instance stores information about the weather conditions
- the WeatherData instance is observed by a BarGraph instance and a LineGraph instance
- when WeatherData changes, it tells BarGraph and LineGraph, and they each update their visual representation of the data
- each object (WeatherData, BarGraph, and LineGraph) has a single, distinct responsility
importantly, the subject does not know the identity of the observer.
hence, observers can be removed or changed without affecting the subject.
e.g., LineGraph could be replaced with PieChart, and WeatherData would be unaffected
the Observer pattern manages the transfer of information between classes without requiring classes to be "tightly coupled"
"coupling" = amount of dependence of one class on another class
- "tightly coupled" = two classes that are highly dependent on each other
- tightly coupled classes cannot exist independently because they rely too heavily on each other to operate in isolation
- one class cannot be changed or replaced without necessitating changes in the dependent class
when to use Observer (from GoF):
- When a change to one object requires changing others, and you don't know how many objects need to be changed.
- When an object should be able to notify other objects without making assumptions about who these objects are.
as we'll see, Observer is the general pattern behind events and event listeners