Observer Pattern in Java

Observer Pattern falls under Behavioural Design Patterns as it studies closely the behaviour of the subject object. This pattern is based on the interdependency of a subject with its observers. The observers study the behaviour of the subject closely and change accordingly whenever a subsequent change is seen in the subject.

Definition

By Definition, the observer pattern provides a one-to-many relationship between subject objects and its observers such that all the subject-dependant elements will be notified when it changes behaviours. The observers will also update in response to the change and deemed necessary.

Structure of the Pattern

Three actors are put to use in this pattern. These are the Subject, Observable, and the Observer.

  • The Subject object is the main object in the pattern. The behaviour of this object is studied closely.
  • Observer objects are those objects that study the subject to look out for changes in the state.
  • Observable objects are those bridge elements that notify the observers of any change in the Subject.

Example and Code

Let us define a publishing house that will notify editors whenever a new script is received by it.

//The class below is the subject class, that is the publishing house

public class PubHouse {
private String script;
private List <Edit>  editor = new ArrayList<>();
public void addEditor (Editor edit) {
editor.add(edit); }
public void removeEditor (Editor edit) {
editor.remove(edit); }

public void giveScript (String script) {
this.script = script;
edit.update(script);
}
}
}

//We will now define the observable editor class

public class Editor implements PubHouse {
private String script;
@override
public void update (Object script) {
this.setScript(String script);
}
}

//Let us assume there is a defined editor interface that will update as soon as a script is received. Now we will add a script to the list.

PubHouse obj1 = new PubHouse ();
Editor obj2 = new Editor ();

obj1.addScript (obj1);
obj2.giveScript(“Script”);

When to use the Observer Pattern

As mentioned in the definition, in this pattern, multiple objects are dependent on one central subject. If your program also has a similar structure when it comes to the relationship between objects, the Observer Pattern is a must use.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.