一、定义

定义对象间的一种一对多的依赖关系,使得每当一个对象的状态改变时,所有依赖于它的对象都会得到通知且被自动更新。

二、类图表示

观察者模式

三、实现

1、Observer

package pattern.behavioral.observer;

public abstract class Observer {

	public abstract void update();
}


package pattern.behavioral.observer;

public class ConcreteObserver extends Observer {

	private String name;
	private ConcreteSubject subject;
	
	public ConcreteObserver(String name, ConcreteSubject subject) {
		this.name = name;
		this.subject = subject;
	}
	
	@Override
	public void update() {
		System.out.println(String.format("Observer %s's new state is: %s", name, subject.getSubjectState()));
	}

}

2、Subject

package pattern.behavioral.observer;

import java.util.ArrayList;
import java.util.List;

public abstract class Subject {

	private List<Observer> observers = new ArrayList<>();
	
	public void attach(Observer observer){
		this.observers.add(observer);
	}
	
	public void detach(Observer observer){
		this.observers.remove(observer);
	}
	
	public void notifyObservers(){
		for(Observer observer : observers){
			observer.update();
		}
	}
}


package pattern.behavioral.observer;

public class ConcreteSubject extends Subject {

	private String subjectState;

	public String getSubjectState() {
		return subjectState;
	}

	public void setSubjectState(String subjectState) {
		this.subjectState = subjectState;
		this.notifyObservers();
	}
	
}

四、使用

package pattern.behavioral.observer;

public class Client {

	public static void main(String[] args) {
		ConcreteSubject subject = new ConcreteSubject();
		subject.attach(new ConcreteObserver("Jack", subject));
		subject.attach(new ConcreteObserver("Tom", subject));
		subject.attach(new ConcreteObserver("Mary", subject));
		
		subject.setSubjectState("ABCDEFG");
		System.out.println();
		subject.setSubjectState("0123456");
	}
}

  • 程序输出:
Observer Jack's new state is: ABCDEFG
Observer Tom's new state is: ABCDEFG
Observer Mary's new state is: ABCDEFG

Observer Jack's new state is: 0123456
Observer Tom's new state is: 0123456
Observer Mary's new state is: 0123456

五、适用场合

  • 当一个对象的改变需要同时改变其他对象,但又不知道具体改变多少对象时

  • 当一个对象的改变必须通知其他对象做出相应的变化,但又不知道通知的对象是谁时