Observer Pattern in java

implementation java explanation

The observer pattern is a design pattern in wich an subject stores a list of all observers that depend on it. When the state of the subject changes, it broadcasts the change to all the observers by calling a method, specific to the observers. The advantage is the fact that observers don’t have to spam the subject to get updates.

Let’s say that we have a reporter that provides multiple news agencies with the news he has gathered. The news agencies call him every day asking for new news, most of the time they’re wasting the time of both parties. So the reporter says that he will make a list of all the news agencies and call them when he has finished his work. The reporter is not interupted by the news agencies, and the news agencies don’t waste everyone’s time by continuously calling the reporter.

Implementation

This is the project’s directory structure. I quite like this way of organizing code. Every class and enum has its own separate file.

ro/xoni/esys
    event
        Event.java
        EventDirection.java
        EventType.java
    observer
        Observer.java
    subject
        Subject.java

The subject

The subject must store the observers that are dependent on it and to dispatch an Event.
The Subject::notifyObservers method is used to dispatch an event.

package ro.xoni.esys.subject;

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

import ro.xoni.esys.event.Event;
import ro.xoni.esys.observer.Observer;

public class Subject {
    public List<Observer> observers = new ArrayList<Observer>();

    public void notifyObservers(Event event) {
        for (Observer observer : observers) {
            observer.update(event);
        }
    }
}

The observer

The observer is responsible for nothing. It really does absolutely nothing. It only has a Observer::update method that does nothing, it’s only used by classes that extend this class and override this method.

package ro.xoni.esys.observer;

import ro.xoni.esys.event.Event;

public class Observer {
    public void update(Event event) {};
}

The event

The event is the actual thing we send to the observer. The event has a type, a direction and a name. You may add other data to the event by creating classes that extend the Event class.

package ro.xoni.esys.event;

public class Event {
    public String name;
    public EventType type;
    public EventDirection direction;

    public Event(String name, EventType type, EventDirection direction) {
        this.name = name;
        this.type = type;
        this.direction = direction;
    }
}
package ro.xoni.esys.event;

public enum EventType {
    PRE,
    POST;
}
package ro.xoni.esys.event;

public enum EventDirection {
    IN,
    OUT;    
}

And this is it. The event system is ready to fire some events.