The Observer Pattern is an example of a behavioral pattern. In object oriented programming, which most of the application nowadays are built of, you cannot talk about it without considering the state of objects. Object oriented programming is all about object interactions. There are cases where objects needs to be informed about the changes of other objects are often. If you want to have a good design, you would want to have to decouple the objects as much as possible for modularity. The observer pattern might be the best pattern for that job.
The Observer Pattern can be used whenever a “subject” needs to be observed by the concrete objects.
Intent:
- Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
How to Implement Observer Pattern:
- Observable – interface or abstract class defining the operations for attaching and de-attaching observers to the client. In the GOF book this class/interface is known as Subject.
- ConcreteObservable – concrete Observable class. It maintain the state of the object and when a change in the state occurs it notifies the attached Observers.
- Observer – interface or abstract class defining the operations to be used to notify this object.
- ConcreteObserver concrete Observer implementations
It is pretty simple how it works. After creating your subject class, it will then instantiate your ConcreteObservable class and set the states of the objects. Then the Observer class checks if there are any update or notifications from the subject and then update is called on to the ConcreteObservers.
The observer pattern is used when:
- the changes in one object also happens in other objects without keeping the object tightly coupled.
- or when our design needs to be enhanced in the future with new observers with minimal changes.
Common example of Observer Pattern:
- Model View Controller Pattern – the observer pattern is used in the model view controller(MVC) architectural pattern. In MVC the observer pattern is used to decouple the model from the view. View represents the Observer and the model is the Observable object.
Observer Pattern in UML Diagram:
I selected this topic because I have read many articles and tutorials about this subject, and since I was making a tutorial about it, I might as well write about it in this blog.
The observer pattern is an exceptional pattern to learn in object oriented design in my opinion. Since, most of the programs written these days are object oriented, it is a good resource to know that when you have a one-to-many dependency between objects, it is useful to use the observer pattern. You can use this pattern to create a notification system for your application.
Reference:
From the blog cs-wsu – Computer Science by csrenz and used with permission of the author. All other rights reserved by the author.