首页 > 代码库 > 设计模式之观察者模式

设计模式之观察者模式

定义:定义了一种一对多的依赖关系,让多个观察都对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。

结构图:


示例代码:

public interface Observer {

	public void update();
}
public class Subject {

	private List<Observer> observers = new ArrayList<Observer>();
	
	public void attach(Observer observer) {
		
		observers.add(observer);
	}
	
	public void detach(Observer observer) {
		
		observers.remove(observer);
	}
	
	public void notify1() {
		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 ConcreteObserver implements Observer {

	private String name;
	private String observerState;
	private ConcreteSubject subject;

	public ConcreteObserver(ConcreteSubject subject, String name) {
		this.subject = subject;
		this.name = name;
	}

	@Override
	public void update() {
		// TODO Auto-generated method stub
		observerState = subject.getSubjectState();
		System.out.println("观察者" + name + "状态是" + observerState);
	}

}
客户端代码如下:

public class Client {

	public static void main(String[] args) {
		
		ConcreteSubject s = new ConcreteSubject();
		s.attach(new ConcreteObserver(s, "x"));
		s.attach(new ConcreteObserver(s, "Y")); 
		s.attach(new ConcreteObserver(s, "Y"));
		s.setSubjectState("ABC");
		s.notify1();
	}
}

运行结果:

观察者x状态是ABC

观察者Y状态是ABC

观察者Y状态是ABC



设计模式之观察者模式