模式结构:
Subject:目标
ConcreteSubject:具体目标
Observer:观察者
ConcreteObserver:具体观察者
UML图:
例子代码:
目标抽象类:
public abstract class Subject {
private List<Observer> observerList = new ArrayList<Observer>();
//添加observer
public void attach(Observer observer){
if(observer != null){
observerList.add(observer);
}
}
//移除observer
public void detach(Observer observer){
if(observer != null){
observerList.remove(observer);
}
}
//通知更新
public void notifyObserver(String state){
for (Observer observer : observerList){
observer.update(state);
}
}
}
具体目标类:
public class ConcreteSubject extends Subject {
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
System.out.println("主题状态重新更改为:" + state);
//状态发生改变 通知各个观察者
this.notifyObserver(state);
}
}
观察者接口:
public interface Observer {
void update(String state);
}
具体观察者一:
public class ConcreteObserver implements Observer {
private String observerState;
@Override
public void update(String state) {
//更新观察者的状态
observerState = state;
System.out.println("ConcreteObserver 监听最新状态:"+observerState);
}
}
具体观察者二:
public class ConcreteObserver1 implements Observer {
private String newState;
@Override
public void update(String state) {
newState = state;
System.out.println("ConcreteObserver1 监听最新状态:"+newState);
}
}
客户类:
public class Client {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
Observer observer = new ConcreteObserver();
Observer observer1 = new ConcreteObserver1();
//注册观察者
subject.attach(observer);
subject.attach(observer1);
//改变主题的状态
subject.setState("new state");
}
}
结果打印: