观察者模式(Observer),定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使他们能够自动更新自己。
Subject类:
package cn.happy.design_pattern._10publishsubscribe; import java.util.ArrayList;
import java.util.List; public class Subject { private List<Observer> observers = new ArrayList<>(); public void attach(Observer observer){
observers.add(observer);
} public void detach(Observer observer){
observers.remove(observer);
} public void mNotify(){
for (Observer item : observers) {
item.update();
}
}
}
Observer类:
package cn.happy.design_pattern._10publishsubscribe; public abstract class Observer { public abstract void update();
}
ConcreteSubject类:
package cn.happy.design_pattern._10publishsubscribe; public class ConcreteSubject extends Subject { private String subjectState; String getSubjectState() {
return subjectState;
} void setSubjectState(String subjectState) {
this.subjectState = subjectState;
} }
ConcreteObserver类:
package cn.happy.design_pattern._10publishsubscribe; public class ConcreteObserver extends Observer { private String name;
private String observerState;
private ConcreteSubject subject; public ConcreteObserver(ConcreteSubject subject, String name) {
this.subject = subject;
this.name = name;
} @Override
public void update() {
observerState = subject.getSubjectState();
System.out.println("观察者"+name+"的新状态是"+observerState);
}
//省略getter and setter
}
测试类:
package cn.happy.design_pattern._10publishsubscribe; public class Mmain { public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
subject.attach(new ConcreteObserver(subject, "X"));
subject.attach(new ConcreteObserver(subject, "Y"));
subject.attach(new ConcreteObserver(subject, "Z"));
subject.setSubjectState("ABC");
subject.mNotify();
} }