Observer pattern is, for me, one of the easiest design patterns, and what is more important – it’s more “natural” than others.
Because it’s nothing new, if you have one object (Observer) which is Observing others object (Subject). Sound and look easy, am I right?
And it is in practice.
Wikipedia have nice, short and clear example of observer pattern: Observer_pattern#Example
But for me it wasn’t enough, so i wrote
There are three files:
- WebsiteGrabber.java – there is declaration and implementation of interface Subject, with three methods (register, unregister and notifyObservers)
- WebsiteObserver.java – declare and fill Observable interface with one method called, of course, update
- WebsiteParser.java – which implements Runnable interface, and do main thing – parse given website to search given word(s).
Why in WebsiteParser.java i use Runnable interface? Mainly because i can create another thread – thread which parse website(s). By this i can be sure that rest of program will work, even if there is no network connection or whatever. (yay, gotta love interfaces!)