Design Patterns In Java
In this design patterns in java series, I will be documenting the most common design patterns as written by the Gang of Four in their classic book: Design Patterns – Elements of Reusable Object-oriented Software.
I will maintain a pattern (no pun intended) of giving a real-world example then show you the code example. Ready? Let us do this!
Real World Example
Design patterns are everywhere in our lives. For example, a newspaper publishing company releases papers each morning and the papers are delivered to their customers/readers by the good old paper boys! So, the company will keep a list of newspaper subscribers in their database somewhere! The readers are free to
Observer Design Pattern Example
In our example, we will have a newspaper publisher as our Subject and the readers as Observers.
Our Subjects will implement this interface!
12345678910 | publicinterfaceISubject{voidregister(IObservero);voidunregister(IObservero);voidnotifyObservers(inti);} |
Our Observers will implement this interface!
123456789 | publicinterfaceIObserver{voidupdate(Strings,inti);} |
Our Subject will look something like this:
123456789101112131415161718192021222324252627282930313233343536373839404142 | publicclassSubjectimplementsISubject{privateintmyValue;privatefinalList<IObserver>observersList=newArrayList<>();publicintgetMyValue(){returnmyValue;}publicvoidsetMyValue(intmyValue){this.myValue=myValue;notifyObservers(myValue);}@Overridepublicvoidregister(IObservero){observersList.add(o);}@Overridepublicvoidunregister(IObservero){observersList.remove(o);}@OverridepublicvoidnotifyObservers(intvalue){for(inti=0;i<observersList.size();i++){observersList.get(i).update(this.getClass().getCanonicalName(),value);}}} |
Then our sample Observer class will look like this:
123456789101112 | publicclassObserverimplementsIObserver{@Overridepublicvoidupdate(Strings,inti){System.out.println("Observer value changed to: "+s+", "+i);}} |
To finally test our design pattern, we need a main method like you would for an entry point into a Java application!
123456789101112131415161718192021222324252627 | publicclassDesignPatternsEx{publicstaticvoidmain(String[]args){System.out.println("designpatterns.DesignPatterns.main()");Subject subject=newSubject();Observer ob=newObserver();subject.register(ob);subject.setMyValue(5);System.out.println("-------");subject.setMyValue(25);System.out.println("-------");subject.unregister(ob);subject.setMyValue(100);}} |
So, in summary, the idea is to let the Subject notify all the Observers (Publisher/Subscriber) whenever a new paper has been printed or released!
You can always view the code used in this example on github!
I hope this tutorial helped you get an idea of how the Observer design pattern works in a general sense of things.
Please share and subscribe (again, no pun intended here) to my future posts on design patterns! Remember, I will be covering all 23 here that are commonly mentioned!
Have a great day and see you soon!