2018-05-10
观察者模式
被观察者
import java.util.ArrayList;
abstract class Subject {
private ArrayList<Observer> observers;
public Subject() {
observers = new ArrayList<>();
}
public void attach(Observer observer) {
observers.add(observer);
}
public void detach(Observer observer) {
observers.remove(observer);
}
public void notifyObserver(int state) {
for(Observer o: observers) {
o.update(state);
}
}
}
class ConcreteSubject extends Subject {
private int subjectState;
public int getState() {
return subjectState;
}
public void setState(int newState) {
subjectState = newState;
System.out.println("subject' state change to " + newState);
this.notifyObserver(subjectState);
}
}
观察者
interface Observer {
public void update(int state);
}
class ConcreteObserver1 implements Observer {
public void update(int state) {
System.out.println("ConcreteObserver1 know state had changed to " + state);
doSomething();
}
private void doSomething() {
System.out.println("ConcreteObserver1 do something!!!");
}
}
class ConcreteObserver2 implements Observer {
public void update(int state) {
System.out.println("ConcreteObserver2 know state had changed to " + state);
doSomething();
}
private void doSomething() {
System.out.println("ConcreteObserver2 do something!!!");
}
}
class ConcreteObserver3 implements Observer {
public void update(int state) {
System.out.println("ConcreteObserver3 know state had changed to " + state);
doSomething();
}
private void doSomething() {
System.out.println("ConcreteObserver3 do something!!!");
}
}
客户端
class Client {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
Observer o1 = new ConcreteObserver1();
Observer o2 = new ConcreteObserver2();
Observer o3 = new ConcreteObserver3();
subject.attach(o1);
subject.attach(o2);
subject.attach(o3);
subject.setState(11);
subject.detach(o2);
subject.setState(12);
}
}