Design patterns interview Questions and answers: observer pattern

The design patterns are very popular with the interviewers and Java/J2EE Job Interview Companion covers GoF design patterns, J2EE design patterns, and EJB design patterns. This blog entry covers the observer design pattern.

Q. What is an observer design pattern?
A. The Observer pattern is a behavioral design pattern that  allows an object (an Observer) to watch another object (a Subject). The subject and observer to have a publish/subscribe relationship. Observers can register to receive events from the Subject.

Some of the practical uses of observer pattern are:

  • When a change to one object requires changing of others, and you don't know how many objects need to be changed.
  • When an object should be able to notify other objects without making assumptions about who these objects are and not tightly coupling them.
  • When a report is received or an event occurs, a message needs to be sent to the subscribed handlers.

Examples:

  • Programming Swing based GUI applications where the listeners register them with events like button click, property change, etc.
  • Programming a stock market application to know when the price of a stock changes.
  • Programming a order placement or trading application to know the status changes like pending, filled, shipped, rejected, etc.

So, whenever you want to have the state change or other information, instead of polling every few second, register the observers with a subject.  






Here is some pseudo code of this third scenario

STEP 1: Define the Subject and Observer interfaces

This is the subject interface


?
1
2
3
4
5
6
7
package com;
 
public interface ReportExecutor {
    public void addHandler(ReportHandler rh);
    public void removeHandler(ReportHandler rh);
    public void processReport(String message);
}


This is the observer interface

?
1
2
3
4
5
6
package com;
 
public interface ReportHandler {
    //handles report
    public void handleMessage(String message);
}


STEP 2: Define the concrete subject and observers.


The concrete subject

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com;
 
import java.util.ArrayList;
import java.util.List;
 
public class SalesReportExecutor implements ReportExecutor {
     
    //list of observers that register their interest in SalesReport
    private List<reporthandler> reportHandlers = new ArrayList<reporthandler>();
 
    @Override
    public void addHandler(ReportHandler rh) {
        reportHandlers.add(rh);
    }
 
    @Override
    public void processReport(String message) {
        for (ReportHandler reportHandler : reportHandlers) {
            reportHandler.handleMessage(message);
        }
    }
 
    @Override
    public void removeHandler(ReportHandler rh) {
        reportHandlers.remove(rh);
 
    }
 
}

The concrete observers

?
1
2
3
4
5
6
7
8
9
10
package com;
 
public class LoggingReportHandler implements ReportHandler {
 
    @Override
    public void handleMessage(String message) {
        //handles report by formatting and printing
        System.out.println("Logging report  " + message);
    }
}


?
1
2
3
4
5
6
7
8
9
10
11
package com;
 
public class EmailReportHandler implements ReportHandler {
 
    @Override
    public void handleMessage(String message) {
        //handles the report by formatting it differently and emailing.
        System.out.println("Emailing report " + message);
        //logic to email report.
    }
}


STEP 3: Finally, the JMS listener class that uses the subject. The JMS Listener class listens on a queue for presence of a report.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.mgl.mts.fix;
 
import javax.jms.Message;
import javax.jms.TextMessage;
 
public class MyAppListener {
 
    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
 
            ReportExecutor executor = new SalesReportExecutor();
            executor.addHandler(new LoggingReportHandler());
            executor.addHandler(new EmailReportHandler());
            executor.processReport(message.toString());
 
        } else {
            throw new IllegalArgumentException("Message must be of type TextMessage");
        }
    }
}

Q. Can you list some Java interfaces that use the observer design pattern?
A.

  • The Java Message Service (JMS) models the observer pattern, with its guaranteed delivery, non-local distribution, and persistence, to name a few of its benefits. The JMS publish-subscribe messaging model allows any number of subscribers to listen to topics of interest. When a message for the published topic is produced, all the associated subscribers are notified.
  • The Java Foundation Classes (JFC) like JList, JTree and the JTable components manipulate data through their respective data models. The components act as observers of their data models.
  • In the java.util package, we have theObserver interface and the Observableclass.
  • In an MVC (Model-View-Controller) architecture, the view gets its own data from the model or in some cases the controller may issue a general instruction to the view to render itself. In others, the view acts as an observer  and is automatically notified by the model of changes in state that require a screen update.


Q. What are the pros and cons of an Observer design pattern?
A. 

PROS:

  • Loose coupling between Subject and Observer: The subject knows only a list of observers, that implement the Observer interface, it does no know the concrete implementation of the Observer.
  • Broadcast communication: An event notification is broadcast to observers irrespective of the number of Observers

CONS:

  • If not used carefully the observer pattern can add unnecessary complexity.
  • The order of Observer notifications is undependable. Simply registering the observers in a particular order will not enforce their order of notification. You don't necessarily know if the first registered listener is notified first or last. If you need to have cascading notifications, where object X must be notified first, followed by object Y, you must introduce an intermediary object to enforce the ordering. 
  • The possibility of a memory leak. A reference to the Observer is maintained by the Subject. Until the Subject releases the reference, the Observer cannot be removed by the garbage collector.

Comments

Popular posts from this blog

SQL Tutorial with HSQLDB

Hibernate tutorial with HSQLDB

Java Interview Questions & Answers: user defined key class