Today I will be talking about a design pattern known as the observer pattern. In a blog put out by the website javapapers.com, the observer pattern is used when multiple objects depend on the state of one object. For example, Class A and Class B rely on the state of Class C and Class D to run. If Class C is in state 0 and Class D is in state 1, Class A will execute and Class B will not. If Class C is in state 1 and Class D is in state 0, Class B will execute and Class A will not. Class A and Class B need to be aware of the state of Class C constantly, and need to know when there is a change in the state of Class C. We can use do this by using observers for Class A and Class B. However, java does not support multiple inheritances; that being a class can’t inherit from more than one parent class. We can use the observer pattern to create observers for objects, which will help objects be aware of the state of different objects.
The blog uses an example using the relationship between a blog and a subscriber. The blog user subscribes to a blog for updates. When a new blog is added, users will be notified of the new blog. In this case, the user is the observer. The UML diagram for this example points out that a subject can have many subscribers. Both the subscribers and the users have implementation classes, which notify the classes of each other’s states. The implementation classes are “observers” in the UML diagram. The subject implementation observer gets and sets the state of the subject, while the user implementation observer updates to see if there are any new changes to the state of subject.
I selected this article to expand on my knowledge of software design patterns. I think they are useful tools to have, and each one has its ideal uses. The observer pattern is good for classes that are related and depend on each others states to function. I learned how I can implement observers for objects for these types of relationships. Now, instead of having the object looking for updates constantly working to search for updates, the observer will do it for them. This leaves the object totally out of the loop, and is only notified when the observer finds a change in state. I hope to implement this pattern in my future projects, as I think it is a great way to keep code efficient, neat, and organized.
Here’s the Link: http://javapapers.com/design-patterns/observer-design-pattern/
From the blog CS@Worcester – The Average CS Student by Nathan Posterro and used with permission of the author. All other rights reserved by the author.