Java Observer Design Pattern Example (original) (raw)

1. Introduction

In this article, we would discuss one of the numerous Java Design Patterns – The Java Observer Design pattern which is being used popularly in a variety of messaging and notification frameworks. The Observer design pattern is a typical way of managing communication between multiple classes. This pattern helps in organising the code in a way that makes it easier to manage and manipulate conversation as needed. This is conceivable just when there are benchmarks set up. These norms ought to be intended to structural or build up the code in a way that is now expected by the new designers. The Java people group has henceforth indicated a few design patterns. In each pattern there are sure pre-characterized coding principles and structures to be pursued. These particular guidelines and the structures of code aid advancement of a code that is sorted out and effectively sensible. Additionally, it likewise finds out that the code is composed in a predefined way and along these lines it is effortlessly reasonable by any new designer joining the undertaking.

With the end goal to guarantee that these coding structures are institutionalised, Java characterises an expansive group of design patterns which spin around the different parts of coding like how we characterise a particular class, how we connect the classes to utilize other, how we use the center highlights of Java like the inheritance and interfaces, the production of items and the administration of protest conduct.

2. Java Design patterns

There are three essential gatherings of these design patterns which are quickly elaborated below. The below sections explain how each pattern has a defined set of rules to work with and how they make your code clean and well-structured.

2.1 Creational Pattern

In software engineering, creational style patterns square measure style patterns that agitate object creation mechanisms, making an attempt to make objects during a manner appropriate to matters. the fundamental kind of object creation may lead to style issues or additional quality to the planning. Creational design patterns solve this downside by somehow dominant this object creation.This gathering of patterns gives five distinctive outline patterns that principally center around the rationale of creation and decimation of objects while covering the genuine execution of the objects. This essentially characterizes the norms for deliberation. Along these lines, this pattern controls the protest access for every module that exists in the application.

2.2 Structural Pattern

Structural design patterns provides further seven different types of patterns. They are concerned with how classes and objects can be composed, to form larger structures. The structural design patterns makes the structure simpler or easier by recognizing the relationships.

2.3 Behavioural Pattern

Behavioural pattern category is mainly concerned with the way objects communicate with each other. Behavioural design patterns are concerned with the interaction and responsibility of objects such as passing messages via connecting one or more classes. They provide eleven different types of patterns to define the communication methodologies.

In this article, we are going to elaborate one of the behavioural patterns – Observer design pattern. According to the encyclopaedia, the observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. This article would explain the concept regarding observer design pattern with a real life example. The below section will represent the pattern logically to explain each component of Observer design pattern. Further on, we will implement Observer design pattern in code.

3. Understanding the Observer design pattern

The ObserverPattern is a proper designpattern to apply in any situation where we have several different objects that are dependent on another object and are required to perform an action when the state of that object changes, or an object needs to notify other objects without knowing that they are or how many there are.

Java Observer Design Pattern

Observer Design Pattern

The main objective of observer design pattern that it defines a one-to-many relationship between objects so that when one object modifies or changes state, all of its dependents objects are notified and updated automatically.

In Observer design pattern the object that is being viewed is called the subject. The objects that are viewing the state changes are called observers or listeners_._

In the above diagram, the Subject class doesn’t update or change the state of dependent objects directly. Instead, Subject class refers to the Observer interface that contains update() method for updating state of depending classes, that makes the Subject class independent of how the state of dependent objects is update.

In above diagram the subject class maintains an observerCollection which is simply the list of currently registered(subscribed) observers. registerObserver(observer) and unregisterObserver(observer) are methods to add and remove observers respectively. notifyObservers() is called when the data is changed or modified and the observers need to be supplied with latest data.

The ConcreteObserverA and ConcreteObserverB classes implement the Observer

Interface by synchronizing their state with subject class state. Both ConcreteObserverA and ConcreteObserverB contains update() method. This way the two dependent classes is notified or update automatically whenever the subject class modifies or changes state.

3.1 Real-Life Example

Let us take a real life example of a celebrity who has many fans. Each of these fans wants to get all the latest updates (images, videos, chats etc.) of his/her favourite celebrity. Hence, he/she can follow the celebrity as long as his/her interest persists. When he loses interest, he simply stops following that celebrity. Here fans are observers and celebrity is a subject.

Java Observer Design Pattern

Observer Design Pattern

4. Implementing Observer design pattern

For the implementation of this pattern let’s take a real life example (Twitter App). In Twitter if we think about a celebrity who has many followers on twitter. Each of these followers wants to get all the latest updates of his/her favourite celebrity. So, he/she can follow the celebrity as long as his/her interest persists. When he/she loses interest, he simply stops following that celebrity. Here we can think of the follower as an observer and the celebrity as a subject. Sometimes this model is also known to as the Publisher-Subscriber model.

Model-View-Controller (MVC) frameworks also use Observer design pattern where Model is the Subject and Views are observers that can register or unregister to get notified of any change or modification to the model.

Moving ahead and implement Observer design pattern using java. Java provides in-built platform for implementing Observer pattern through java.util.Observable class and java.util.Observer interface.

Java.util.Observable class and java.util.Observable class are used to create subclasses that other parts of the program can observe. When an object of such subclass undergoes a change, observing classes are notified.

Let us implement observer design pattern with Celebrity Follower Example. Here Followers can register them-self to get updates on any update with Celebrity and same way they can lose it or they can unregister if they have no interest any more, Followers are acting as an Observer and Celebrity will act as a Subject

Subject.java

123456 class Subject{public void register(Observer o);public void unregister(Observer o);public void notifyAllObservers(String s);}

Observer.java

01020304050607080910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 interface Observer{public void update(String name, String s);}class Celebrity implements Subject{private String celebrityName; private ArrayList followers; public Celebrity(String celebrityName) {this.celebrityName = celebrityName;followers = new ArrayList();}@Overridepublic void register(Observer o) {followers.add(o);System.out.println(o + " has started following " + celebrityName);}@Overridepublic void unregister(Observer o) {followers.remove(o);System.out.println(o + " has stopped following " + celebrityName);}@Overridepublic void notifyAllObservers(String tweet) {for(Observer follower : followers){follower.update(celebrityName, tweet);}System.out.println();}public void tweet(String tweet){System.out.println("\n" + celebrityName + " has tweeted :: " + tweet + "\n");notifyAllObservers(tweet);}}class Follower implements Observer{private String followerName;public Follower(String followerName) {this.followerName = followerName;}@Overridepublic void update(String celebrityName , String tweet) {System.out.println(followerName + " has received "+ celebrityName + "'s tweet :: "+ tweet);}@Overridepublic String toString() {return followerName;}}

In the above code, a class Subject represents a class that includes basic three functions register, unregister, notifyAllObservers.

In the above code an interface Observer implements that has only one abstract method called update(). In the next step we will create Celebrity class and Follower class that implement Observer class.

Now, we will implement ObserverDesignPattern Class that includes instances (objects) of Celebrity class and Follower class.

ObserverDesignPattern.java

01020304050607080910111213141516171819202122232425262728293031323334353637383940414243 public class ObserverDesignPattern {public static void main(String[] args) {Celebrity salmankhan = new Celebrity("Salman Khan");Celebrity ranbirkapoor = new Celebrity("Ranbir Kapoor");Follower jay = new Follower("Jay");Follower rajan = new Follower("Rajan");Follower raj = new Follower("Raj");Follower vijay = new Follower("Vijay");Follower amit = new Follower("Amit");Follower harsh = new Follower("Harsh");salmankhan.register(jay);salmankhan.register(raj);salmankhan.register(amit);ranbirkapoor.register(rajan);ranbirkapoor.register(vijay);ranbirkapoor.register(harsh);salmankhan.tweet("Hey guys, came across this interesting trailer, check it out.");ranbirkapoor.tweet("Good Morning..!!");salmankhan.unregister(rajan);salmankhan.tweet("Teaser of Secret Superstar has been released..!!");}}

5. Benefits of using Observer Design Pattern

The Observer Design Pattern provides us with the following advantages/benefits.

Observer pattern provides this loose coupling as:

6. Use of Observer Design Pattern

Till now, we have discussed the concept of observer pattern, implementation of this pattern and its benefits. The Observer design pattern can be used in the following areas:

7. Demerits of Observer Design Pattern

The Observer pattern consists of several drawbacks that are mentioned below:

8. Observer Design Pattern – Conclusion

A programming world without design patterns would feature much hard work and redundancy while developing program. And yet, the regretful fact is many developers and programmers don’t use design patterns half enough.

The observer design pattern provides the kind of strength we’ve come to expect from patterns. It allows for multiple observing classes to be updated or modified as and when data changes occur in observable class. This asynchronous update approach avoids the need for expensive polling mechanisms in that the observer continuously (and unnecessarily) asks for updates

9. Download the Source Code

The above code example can be downloaded from the below link.

Download
You can download the full source code of this example here: ObserverPattern.zip

Photo of Abhishek Kothari

Abhishek is a Web Developer with diverse skills across multiple Web development technologies. During his professional career, he has worked on numerous enterprise level applications and understood the technological architecture and complexities involved in making an exceptional project. His passion to share knowledge among the community through various mediums has led him towards being a Professional Online Trainer, Youtuber as well as Technical Content Writer.