- 当ConcreteSubject的状态发生改变时,会调用其内部的方法Notify(),该方法内部会对每一个监听它的观察者发出update通知
public interface Observer {
void update();
}
public class ConcreteObserver implements Observer {
private String name;
private String observerState;
private ConcreteSubject concreteSubject;
public ConcreteObserver(String name, ConcreteSubject concreteSubject) {
this.name = name;
this.concreteSubject = concreteSubject;
}
@Override
public void update() {
observerState = concreteSubject.getSubjectState();
System.out.println("观察者 " + name + " 的新状态是 " + observerState);
}
}
import java.util.ArrayList;
import java.util.List;
public abstract class Subject {
private List<Observer> observers = new ArrayList<>();
public void add(Observer observer) {
observers.add(observer);
}
public void remove(Observer observer) {
observers.remove(observer);
}
public void Notify() {
for (Observer observer : observers) {
observer.update();
}
}
}
public class ConcreteSubject extends Subject {
private String subjectState;
public String getSubjectState() {
return subjectState;
}
public void setSubjectState(String subjectState) {
this.subjectState = subjectState;
}
}
public class Main {
public static void main(String[] args) {
ConcreteSubject concreteSubject = new ConcreteSubject();
concreteSubject.add(new ConcreteObserver("A",concreteSubject));
concreteSubject.add(new ConcreteObserver("B",concreteSubject));
concreteSubject.add(new ConcreteObserver("C",concreteSubject));
concreteSubject.setSubjectState("改变的状态");
concreteSubject.Notify();
}
}