Core Java

Java Observer Design Pattern Example

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 Observer Pattern is a proper design pattern 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

1
2
3
4
5
6
//This Class handles adding, deleting and updating all observers
class Subject{
public void register(Observer o);
public void unregister(Observer o);
public void notifyAllObservers(String s);
}

Observer.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//The Observers update method is called when the Subject changes
interface Observer{
public void update(String name, String s);
}
//This class extends Subject interface.
class Celebrity implements Subject{
private String celebrityName;  //name of the celebrity
private ArrayList<Observer> followers;  //list of followers
public Celebrity(String celebrityName) {
this.celebrityName = celebrityName;
followers = new ArrayList<Observer>();
}
//add follower to the celebrity's registered follower list
@Override
public void register(Observer o) {
followers.add(o);
System.out.println(o + " has started following " + celebrityName);
}
//remove follower from celebrity's registered follower list
@Override
public void unregister(Observer o) {
followers.remove(o);
System.out.println(o + " has stopped following " + celebrityName);
}
//Notify all the registered followers
@Override
public void notifyAllObservers(String tweet) {
for(Observer follower : followers)
{
follower.update(celebrityName, tweet);
}
System.out.println();
}
//This method updates the tweet.
// It will internally call notifyAllObservers(tweet) method
//after updating the tweet.
public void tweet(String tweet)
{
System.out.println("\n" + celebrityName + " has tweeted :: " + tweet + "\n");
notifyAllObservers(tweet);
}
}
// This class extends Observer interface.
class Follower implements Observer{
private String followerName;
public Follower(String followerName) {
this.followerName = followerName;
}
//This method will be called to update all followers regarding the new tweet posted by celebrity.
@Override
public void update(String celebrityName , String tweet) {
System.out.println(followerName + " has received "+ celebrityName + "'s tweet    :: "+  tweet);
}
@Override
public 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

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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.

  • Its main advantage is that it supports the concept of loose coupling between objects that interact with each other. i.e., they provide loose coupling between objects called observer and observable. Loosely coupled objects are flexible with changing requirements. Here loose coupling means that the interacting objects should have less information about each other.

Observer pattern provides this loose coupling as:

  • Subject class only knows that observer implement Observer interface. That’s it.
  • There is no need to modify or change Subject class to add or remove observers.
  • We can reuse subject and observer classes independently of each other.
  • Observer design pattern allows sending data to other objects effectively without any change in the Subject or Observer classes. Whenever the Subject class modifies or changes state it immediately sends data to the Observer class without any change.
  • Observers can be added/removed at any point in time.

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:

  • It is primarily used when one object(Subject Class) changes its state, then all other dependents object(Observer Class) must automatically change their state to maintain uniformity.
  • Another way it can be used when Subject class doesn’t know about number of Observer classes it has.
  • Observer pattern can be used when a depending object should be able to notify all other dependent objects without knowing that objects are

7. Demerits of Observer Design Pattern

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

    • When using Observer design pattern sometimes whenever any problem encountered debugging becomes very tough because flow of control is completely between observers and observable also we can predict that now observer is going to fire and if there is bond between observers then debugging become more complex.
    • Another problem with this pattern is memory management because subject class will hold all the reference of all the observers’ class and if we didn’t remove the object it can create a memory issue.
    • If the Observer design pattern is not perfectly implemented, the Observer class can add complexity and lead to unintentional performance issues.
  • The most important problem of observer design pattern is the issue of memory leak. Memory

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

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button