Step 3
Use the Game's template method play() to demonstrate a defined way of playing game.
We have observers listen to a subject. When the subject has changed its state, all the observers will get updated.
public class BinaryObserver extends Observer{
@Override
public void update(int state) {
System.out.println( "Binary String: " + Integer.toBinaryString( state ) );
}
}
public class OctalObserver extends Observer{
@Override
public void update(int state) {
System.out.println( "Octal String: " + Integer.toOctalString( state ) );
}
}
BinaryObserver.java
OctalObserver.java
public abstract class Observer {
public abstract void update(int state);
}
Observer.java
public class Subject {
private Observer binaryObserver = BinaryObserver();
private Observer octalObserver = OctalObserver();
private int state;
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
public void notifyAllObservers(){
binaryObserver.update(this.state);
octalObserver.update(this.state);
}
}
Subject.java
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
System.out.println("First state change: 15");
subject.setState(15);
System.out.println("Second state change: 10");
subject.setState(10);
}
}
ObserverPatternDemo.java
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();
}
}
}
Subject.java
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() ) );
}
}
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() ) );
}
}
BinaryObserver.java
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
OctalObserver.java
Observer.java
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);
}
}
ObserverPatternDemo.java