--referenced from the book "Head First Design Pattern."
Publishers + Subscribers = Observer Pattern
Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified,
Its dependent objects are to be notified automatically. It is also a behavioural pattern.
There some key components in Observer pattern:
Subject object: Subject is an object that maintains a list of its dependents, called observers. and notifies them automatically of any state changes, usally by calling one of their methods.
Observer object:
Below is a logical flow of Observer pattern example:
Step 1. Create Observer abstract class:
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
Step 2. Subject Class
import java.util.ArrayList;
import java.util.List;
public class Subject {
private List<Observer> observers = new ArrayList<Observer>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
public void attach(Observer observer){
observers.add(observer);
}
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
}
Step 3. Create Concrete Observer class
1. BinaryObserver
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Binary String: " + Integer.toBinaryString( subject.getState() ) );
}
}
2. OctalObserver
public class OctalObserver extends Observer{
public OctalObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Octal String: " + Integer.toOctalString( subject.getState() ) );
}
}
3. HexaObserver
public class HexaObserver extends Observer{
public HexaObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Hex String: " + Integer.toHexString( subject.getState() ).toUpperCase() );
}
}
Step 4. ObserverPatternDemo
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new HexaObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);
System.out.println("First state change: 15");
subject.setState(15);
System.out.println("Second state change: 10");
subject.setState(10);
}
}
There is Java built-in support for Observer patter.
"Head first Java"