观察者模式
观察者模式有两个核心对象,主题和观察者,一般来说主题不用知道谁是他的观察者,只需要调用方法通知全体,但其缺点是必须依赖于这些观察者对象,这可以通过依赖委托来改进,这种模式能够实现解耦,让双方都依赖于抽象而不依赖具体,通常用在观察者自身改变时也需要改变和他一样的观察者的状态
Subject.java
public abstract class Subject {
List<Observer> observerList = new ArrayList<>();
public void add(Observer observer){
observerList.add(observer);
}
public void delete(Observer observer){
observerList.remove(observer);
}
public void send(){
for (Observer observer:observerList){
observer.modify();
}
}
}
SpecificSubject.java
public class SpecificSubject extends Subject {
private String subjectState;
public String getSubjectState() {
return subjectState;
}
public void setSubjectState(String subjectState) {
this.subjectState = subjectState;
}
}
Observer.java
public abstract class Observer {
public abstract void modify();
}
SpecificObserver.java
public class SpecificObserver extends Observer {
private SpecificSubject subject;
private String name;
private String observerState;
public SpecificObserver(SpecificSubject subject, String name) {
this.subject = subject;
this.name = name;
}
public SpecificSubject subject(){
return subject;
}
@Override
public void modify() {
observerState = subject.getSubjectState();
System.out.println(name+" "+observerState);
}
}
TestObserver.java
public class TestObserver {
public static void main(String[] args) {
SpecificSubject subject = new SpecificSubject();
subject.setSubjectState("ok");
Observer observer1 = new SpecificObserver(subject,"one");
Observer observer2 = new SpecificObserver(subject,"two");
subject.add(observer1);
subject.add(observer2);
subject.send();
}
}
Run result
one ok
two ok