Open cxlove opened 8 years ago
step 1: naive design for weather station. if the data update, we called each display element.
So if we add a new display element, we need to add the code in WeatherData. And even more troubling is that if we change the data interface, we must to change the code for all displays in WeatherData.
step 2: build Subject and Observe object, using interface to interact between them, support register & unregister & notify
In our example, the weather station or weather data is the Subject. So it implements from a Subject interface which support register & unregister & notify. And some different DisplayElements is the Observer. It implements from a DisplayElement which support display and a Observer which support observed multiple Subjects.
The DisplayElement don't need to know how Subject implemented, because it just use some interfaces to interact with Subject. And Subject also don't need to know what is the difference for different types of Observer, beacuse it also just use some same interfaces to interfact with all of Observers. It's convenient to add a new DisplayElement or Observer.
step 3, using the java.util which is support observer pattern
There are some shortcoming for using java.util to support observer pattern. The Observable in util is a class ,we need to inherit it. But it's trouble to extend the Observable which is againist the principle, favor composition over inheritance.
For example, now we have some Observable, different journals which base on a super class, need to support. It's inconvenient to support multiple inheritance. The setChanged function in Observable is protected, so you can't use it unless you inherit it.
RT