观察者模式:定义对象之间的一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自己更新自己。
public abstract class Component {
private List<Observer> observers = new ArrayList<>();
public void add(Observer observer) {
observers.add(observer);
}
public void delete(Observer observer) {
observers.remove(observer);
}
public void notifys() {
for (Observer observer : observers) {
observer.update();
}
}
}
public class ConcreteComponent extends Component {
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
public abstract class Observer {
public abstract void update();
}
public class ConcreteObserver extends Observer {
private String name;
private String state;
private ConcreteComponent concreteComponent;
public ConcreteObserver(String name, ConcreteComponent concreteComponent) {
this.name = name;
this.concreteComponent = concreteComponent;
}
@Override
public void update() {
state = concreteComponent.getState();
System.out.println("观察者" + name + ",的新状态是" + state);
}
public ConcreteComponent getConcreteComponent() {
return concreteComponent;
}
public void setConcreteComponent(ConcreteComponent concreteComponent) {
this.concreteComponent = concreteComponent;
}
}
public class ObserverDemo {
public static void main(String[] args) {
ConcreteComponent component = new ConcreteComponent();
component.add(new ConcreteObserver("AA", component));
component.add(new ConcreteObserver("BB", component));
component.add(new ConcreteObserver("CC", component));
component.setState("XYZ");
component.notifys();
}
}