Thursday, December 27, 2018

Observer Pattern

I have been sitting on this blog for a while. I finished the chapter a while ago, but not sure exactly why I wasn't getting to writing the blog post. At one time I had a few blogs written so I could just post, then I got sick or something and fell behind. I am obviously not as prepared as I was at that time. I am not going to make any promises because, when it comes to blogging, I don't usually keep the promise to write once time a week. At this point I am once a month. Let's put it out there. I will write one blog a month.

Let's start (and finish) December with Observer Pattern. The thought behind the Observer Pattern is pretty simple, objects subscribe to events and when that event happens the object will get notified. It is very similar to a newspaper model (except we hope the Observer Pattern doesn't get the same fate of newspapers). The object is an observer, or subscriber, to the subject, or publisher. Each morning a paper gets published and sent to everyone that subscribes to it. One can unsubscribe from the newspaper at anytime in order to stop receiving the papers, or new people can subscribe at any time.

Each object should implement an interface subject and all observers should implement an observer interface. The concrete observer will register with a concrete subject to receive updates.The concrete subject will contain methods to add or remove subscribers.

When the observer is subscribed to the subject anytime a change in the subject happens the observer will be notified. If the observer gets tired of receiving the notifications it can unsubscribe. This pattern allows for loose coupling:

  • The only thing the subject knows about an observer is that it implements a certain interface
  • We can add new observers at any time
  • We never need to modify the subject to add new types of observers
  • We can reuse subjects or observers independently of each other
  • Changes to either the subject or an observer will not affect the other

Loosely coupling allows for a pretty flexible design and will minimize the number of changes that we have to make if any changes need to make changes.

Different frameworks already have ways to do the Observer Pattern, in Java there is a built-in observable class in the java.util package. And C# you can use delegates and events. It will take a little research to find the correct way to implement the Observer Pattern in whatever you are using, or you can implement your own (probably not the most effective way to do it) as I did in the link below:

Link to my example

Alright, next up? Good question, but I want to get Google Analytics or some sort of analytics on jorgfam.com. We will see what January brings.


"Maybe Christmas, the Grinch thought, doesn't come from a store." - Dr. Seuss

No comments: