主题类
package demo;
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();
}
}
}
观察者抽象类
package demo;
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
观察者子类A
package demo;
public class AObserver extends Observer{
public AObserver(Subject subject){
this.subject = subject;
subject.attach(this);
}
@Override
public void update() {
System.out.println( "观察者A 更新了状态: "+subject.getState());
}
}
观察者子类B
package demo;
public class BObserver extends Observer{
public BObserver(Subject subject){
this.subject = subject;
subject.attach(this);
}
@Override
public void update() {
System.out.println( "观察者B 更新了状态: "+subject.getState());
}
}
测试类
package demo;
public class demo1 {
public static void main(String[] args) {
Subject subject = new Subject();
new AObserver(subject);
new BObserver(subject);
subject.setState(8);
System.out.println("---------分割线---------");
subject.setState(88);
}
}
运行结果
观察者A 更新了状态: 8
观察者B 更新了状态: 8
---------分割线---------
观察者A 更新了状态: 88
观察者B 更新了状态: 88
网友评论