Thursday, November 12, 2015

HeadFirst Design Pattern: Ch2 Observer Pattern

Nothing special here just an example about the Observer (publish subscribe) pattern,

So as we know, the publisher is called a Subject.

We should have a Subject Interface and an Observer Interface

the example was about WeatherData, the WeatherData will be updated and other Observers are interested in this update

here is the general picture of the observer pattern 


and the Wheather Example is Like this




the Display interface in the picture above is some extra functionality required by the observers, but sure it is not related to the observer patterns


and the code is

1- the interface definition



2- implementing the Subject interface
3- implementing the Observer interface


4- The main




Java and Observer Pattern
another thing that you should know is that java has an already built in Observer and Subject classes, you can use them to build your observer patterns the classes are java.util.Observable (The subject) and java.util.Observer (the observer)

The only problem is that Observable is not an interface, it is a class.


OO Principle
Strive for loosely coupled objects: The observer pattern is an example, the subject and observer are loosly coupled.


No comments:

Post a Comment