Observer Design Pattern

The Observer Design Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

A typical Example

Let us take a real-life implementation of the Observer Design Pattern. A newsletter with sales and new products of the shop is the subject. All the subscribers in this newsletter are observers.

Every time a new product is added to the shop, the marketing sends a newsletter. It might include media, such as video and photos of the product. The subscribers are notified about the new product.

In this example, the subscribers are observers, and the store is the subject.

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

Observable classes are used to create subclasses that other parts of the program can observe. When an object of such subclass changes, observing classes are notified.

Implementation

Let us implement an observer design pattern with the Shop Newsletter example. Subscribers can register themselves to get updates on any news of the Shop. In the same way, they can unsubscribe if they have no interest anymore. Subscribers are acting as Observers, and Store will act as a Subject.

Let’s assume that a store wants to notify its loyal customers of an ongoing sale. The system would send a short message to all subscribed customers whenever a sale has been activated.

In the pattern, the Observer is defined as a Java Interface.

 

public interface Observer {
   public void notification(String handle, String news);
}

 

The Subject is also defined as a Java Interface, with methods that add, removes, and notifies the observers.

 

public interface Subject {
  public void addSubscriber(Observer observer);
  public void removeSubscriber(Observer observer);
  public void notifySubscribers(String email);
}

 

In this example, the store is the Subject. It contains a list of observers, which are all subscriptions to the news of the store.

 

import java.util.ArrayList;
import java.util.List;

public class Store implements Subject {

    protected List<Observer> observers = new ArrayList<Observer>();
    protected String name;
    protected String news;

    public Store(String name) {
        super();
        this.name = name;
        this.news = " - FROM : " + name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEaddress() {
        return news;
    }
    public void sendNews(String news) {
        System.out.printf("\nName: %s, News : %s\n", name, news);
        notifySubscribers(news);
    }
    @Override
    public synchronized void addSubscriber(Observer observer) {
        observers.add(observer);
    }
    @Override
    public synchronized void removeSubscriber(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifySubscribers(String n) {
        observers.forEach(observer -> observer.notification(news, n));
    }
}

 

People who are subscribed implements the Observer Interface. They register the name and get notifications.

 

public class Subscriber implements Observer {

    protected String name;
    public Subscriber(String name) {
        super();
        this.name = name;
    }
    @Override
    public void notification(String handle, String news) {
        System.out.printf("%s received news: %s - NEWS: '%s'\n",name, handle, news);
    }
}

 

The application class declares objects of stores and subscribers, sends notifications and removes subscribers.

 

public class EmailSystem {
  public static void main(String args[]) {
    Store n1 = new Store("21Store");
    Subscriber s1 = new Subscriber("Viki");
    Subscriber s2 = new Subscriber("Rachel");
    n1.addSubscriber(s1);
    n1.addSubscriber(s2);
    n1.sendNews("Summer sales!");
    n1.removeSubscriber(s2);
    n1.sendNews("Only in August");
  }
}

 

In Console:

Name: 21Store, News : Summer sales!
Viki received news:  - FROM : 21Store - NEWS: 'Summer sales!'
Rachel received news:  - FROM : 21Store - NEWS: 'Summer sales!'

Name: 21Store, News : Only for new arrivals
Viki received news:  - FROM : 21Store - NEWS: 'Only in August'

 

The Observer Design Pattern is a very popular design pattern, so try to understand its principle because you might use it.

For more Java Examples, visit Code in Java

Keep coding…