Observer - Behavioral Design Pattern
2019, Feb 12
🕵 Observer
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
abstract class Observer {
protected Subject subject;
public abstract void update();
}
class Subject {
private List<Observer> observers = new ArrayList<>();
private int state;
public void add(Observer o) {
observers.add(o);
}
public int getState() {
return state;
}
public void setState(int value) {
this.state = value;
execute();
}
private void execute() {
for (Observer observer : observers) {
observer.update();
}
}
}
class HexObserver extends Observer {
public HexObserver(Subject subject) {
this.subject = subject;
this.subject.add(this);
}
public void update() {
System.out.print(" " + Integer.toHexString(subject.getState()));
}
}
class OctObserver extends Observer {
public OctObserver(Subject subject) {
this.subject = subject;
this.subject.add( this );
}
public void update() {
System.out.print(" " + Integer.toOctalString(subject.getState()));
}
}
class BinObserver extends Observer {
public BinObserver(Subject subject) {
this.subject = subject;
this.subject.add(this);
}
public void update() {
System.out.print(" " + Integer.toBinaryString(subject.getState()));
}
}
public class ObserverDemo {
public static void main( String[] args ) {
Subject sub = new Subject();
// Client configures the number and type of Observers
new HexObserver(sub);
new OctObserver(sub);
new BinObserver(sub);
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.print("\nEnter a number: ");
sub.setState(scan.nextInt());
}
}
}