The Observer Pattern - Implementation exercises
This is a Background Lab session for DACSS/PASSC.
Example problem
A temperature sensor gives the current values of the measured temperature. In this exercise, the sensor data values will be directly set in the test driver program.
The measured temperature values can be used by different display components:
- A NumericDisplay, which simply displays the numeric value of the current temperature
- A TextDisplay, which displays the text cold if the current temp is under 20, else displays warm
- An AverageDisplay, which displays the average value of all the temperatures recorded during the period when the component is attached.
Every time the sensor data changes, all the attached displays must update.
Displays can be dynamically attached and detached.
The design solution will be based on the Observer pattern, with the mappings:
- ConcreteSubject = TemperatureSensor
- ConcreteObservers = NumericDisplay, TextDisplay, AverageDisplay
You can find a short presentation of the observer pattern and its mapping on the example here.
Task 1
Implementation decision: Choose the PUSH approach for passing temperature values.
Complete the implementation given in the presentation (add the other concrete observers) and run the testprogram.
Task 2
Extend the temperature sensor with following data: the sensor ID, the location, the date of its technical revision, its metrological precision.
TextDisplay will show the location information and the warm/cold category, the NumericDisplay will show the location, the metrological precision and the value of the current temperature, the AverageDisplay will show all the sensor data and the computed average temperature.
Change the data transmission policy to work according the PULL approach.
In this second version, your test program will have multiple instances of TemperatureSensor, and each display component can be attached to several sensors.
Task 3
Write an interactive program, where you can repeatedly select the following options from a menu:
- Create a new temperature sensor. Input sensor data and initial temperature value.
- Create a new display (text, numeric or average)
- Attach an existing display to one of the existing temperature sensors. A sensor will have multiple displays attached. A display can be attached to multiple sensors.
- Detach a display from a sensor
- Set a new temperature value to one of the sensors. All the attached displays must update.