Home Java Design Patterns: Observer Pattern In Java

Design Patterns: Observer Pattern In Java

0
604

[thirstylink ids=”2322″]Amazon Fire TV Stick with Voice Remote | Streaming Media Player[/thirstylink]

The Gang-Of-Four design patterns are a legend and they have been incorporated into most of the projects that the developers are working on. The design patterns are divided into three broad categories – Creational, Structural, and Behavioral. In this journal entry, we will be taking a look at Observer Pattern– one of the Behavioral Design Pattern.

Observer design pattern is also called as publish-subscribe pattern. Some of its implementations are;

  • java.util.EventListener in Swing
  • javax.servlet.http.HttpSessionBindingListener
  • javax.servlet.http.HttpSessionAttributeListener

Observer Pattern

As the name suggests, is used in scenarios when you are interested in the state of an object and want to get notified whenever there is any change. In observer pattern, the object that watches on the state of another object is called Observer and the object that is being watched is called Subject. In order for the Observer to get notified, they have to register themselves with the Subject individually. The Subject needs to provide the following the methods for the Observer: addObserver(), removeObserver(), and notifyObserver().

Let’s understand this using an example from an eCommerce background. One of the major e-commerce site is running a promotion for the upcoming mobile. They want the users to register themselves by providing their email address or by registering as a customer on their site. In this scenario, the e-commerce site is the Subject and the customers registering are the Observers.

The customers registered will be notified once that promotional mobile is available in the store. The customers also have the option to de-register themselves from the site if they are not looking forward to that mobile.

Now let’s look at the above scenario using an example and implement the above pattern.

What functionalities are required by the Subject?

  • Add / Register a Customer
  • Remove / DeRegister a Customer
  • Notify the Customers

public interface Subject {

	public void addCustomer(Observer o);

	public void removeCustomer(Observer o);

	public void notifyCustomer();
}


public void MobileDevice implements Subject {
	
	// List of Customers Registered for Notification
	private ArrayList<Observer> customers = new ArrayList<Observer>();

	// State of Mobile Device
	private boolean inStock = true;

	// Getter for inStock
	public boolean isInStock() {
		return inStock;
	}

	// Setter for inStock
	public void setInStock(boolean inStock) {
		this.inStock = inStock;
		notifyCustomer();
	}

	@Override
	public void addCustomer(Observer o) {
		customers.add(o);
	}

	@Override
	public void removeCustomer(Observer o) {
		customers.remove(o);
	}

	@Override
	public void notifyCustomer() {
		// Logic implementation to notify the users
	}

}

What functionalities are required by Observer?


public interface Observer {

	// Called by the Subject
    publid void update();

}


public void Customer implements Observer {
	
    private Subject subject = null;

    public Customer(Subject subject) {
        this.subject = subject;
    }

    @Override
    public void update() {
        buyMobile();
        unsubscribe();
    }

    public void buyMobile() {
        // Logic to buy the mobile by the Customer
    }

    public void unsubscribe() {
        subject.removeCustomer(this);
    }

}

Observer & Subject are loosely coupled. Change to one will not impact other.

Let’s understand this using the Class Diagram also.

Observer Pattern