Hello, welcome to my new article on advanced Java programming. Today, we will talk about the Observer interface and Observable class of Java programming language and how we can use this to implement a small MVC architecture. I am pretty sure you know about MVC – It stands for Model, View and Controller.

About the Problem

Let’s talk about a CLI chat application, where the user types a single line message and send it to the other end. In this CLI chat application will ignore any non-alphabetic character typed in the single-line message with ‘*’, say this is to make the message safer.

Let’s break down the problem,

  1. The Input or the CLI is taken care of by one component.
  2. The message is stored in a message queue component and the queue is designed to hold one single line message as a sequence of characters.
  3. If the last character in the queue is a new line, it should send the message. For this, we need a messaging component.

Let’s map the problem statements into Model, View, and Controller

Model

Here the message queue which holds the single-line message data is our Model. It should change the state every time the Controller sends a character after filtering.

View

The messaging component is our View in this scenario. Whenever the Model changed and the last character is a new line, it has to pick that message and send it to the other side.

Controller

The component which listens to the keyboard events is our Controller. The Controller reads the character and replaces it with ‘*’ if it is a non-alphabetic and trigger update on Model.

Let’s be practical. Now we will see how we can use the Java built-in Observer interface and Observable class to solve this problem.

About Observer and Observable

These two can be used to implement our MVC architecture as these two together gives us the Observer design pattern.

An Observer instance listens to the changes in an Observable instance.

  1. The Observable instance must be capable of a state change.
  2. The Observable instance must have at least one Observer.
  3. The Observer instance must detect and process the Observable instance state change.

Creating an Observer instance

  1. The Java utility package provides an interface called Observer.
  2. The Observer interface has an abstract method called update().
  3. The implementing class must provide the state change processing logic on the update() method.


package org.sydlabz.mvc;
import java.util.Observer;
import java.util.Observable;
public class MessageListener implements Observer {
@Override
public void update(Observable messageQueue, Object prameters) {
// Handle the state change here.
}
}

Creating an Observable instance

  1. The Java utility package provides a class named Observable.
  2. A class must extend Observable in order to become an observable instance.


package org.sydlabz.mvc;
import java.util.Observable;
public class MessageQueue extends Observable {
public MessageQueue() {
// Initialize the message queue.
}
}

Registering with an Observer instance

Once created, an observable instance must register to at least one observer instance in order to notify the state change to the observer. The Observable.addObserver(Observer ) method is used for this.


package org.sydlabz.mvc;
public class MVC {
public static void main(String[] args) {
MessageQueue messageQueue = new MessageQueue();
MessageListener messageListener = new MessageListener();
messageQueue.addObserver(messageListener);
}
}

view raw

MVC.java

hosted with ❤ by GitHub

Notifying Observers

To notify all the observers or a single observer, the observable instance must identify the state change with the Observable.setChanged() method and notify them with Observable.notifyObservers(). This usually happens when the user sends a character input from the CLI. The code is given below.


// Inside MVC.main(String[] )
public static void main(String[] args) {
MessageQueue messageQueue = new MessageQueue();
MessageListener messageListener = new MessageListener();
messageQueue.addObserver(messageListener);
CLI cli = CLI.getInstance(System.in);
while (true) {
char input = (char )cli.read();
if (Chararcter.isAlphabetic(input) || input == '\n') {
messageQueue.add(input);
} else {
messageQueue.add('*');
}
}
}
// Inside MessageQueue.add(char input)
public void add(char input) {
if (input == '\n') {
setChanged();
notifyObservers();
} else {
message.append(input);
}
}

view raw

MVCDemo1.java

hosted with ❤ by GitHub

Sending the Message

Okay, its time for us to send the chat message to the other. This must be addressed in our Observer.update() method. Here when we call messageQueue.getMessage() it will reset the message queue to get the next sequence of characters.


// Inside MessageListener.update(Observable , Object )
public void update(Observable messageQueue, Object parameters) {
if (messageQueue instanceof MessageQueue) {
MessagingService messagingService = MessagingService.getInstance();
messagingService.send(userId, messageQueue.getMessage());
}
}

view raw

MVCDemo2.java

hosted with ❤ by GitHub

With the above said, we have done with our MVC architecture.

  1. Main class acts as a Controller and it is responsible for accepting user inputs and displaying the details. (you can make it is a controller class instead of a static method) which connects the View with the model
  2. MessageQueue is the Model, which is being updated by the Controller.
  3. Here the View is the MessageListener, which listens or observe the Model for a state change.

Hope this helps  you in understanding the Observer interface and Observer class of the Java programming language. If you have any questions or suggestions please post it as a comment 🙂

Thanks

Seyed F

Advertisement