观察者设计模式

观察者模式是一种常见的设计模式,用于当被观察者的状态更新时,通知所有已注册的观察者。
//定义被观察者,可以是接口或抽象类
public abstract class Subject {

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

//定义具体的被观察者
public class ConcreteSubject extends Subject{

	private String subjectState;

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

	public String getSubjectState() {
		return subjectState;
	}

}


//定义观察者,可以是接口或抽象类
public abstract class Observer {

	abstract void update();
}

//定义具体观察者
public class ConcreteObserver extends Observer{

	private String name;
	private ConcreteSubject concreteSubject;
	
	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	public ConcreteObserver(ConcreteSubject concreteSubject,String name){
		this.concreteSubject = concreteSubject;
		this.name = name;
	}
	
	@Override
	void update() {
		System.out.println(getName()+"#is updating subject:#"+concreteSubject.getSubjectState());
	}

}

//测试类
public class Client {

	public static void main(String[] args) {
		ConcreteSubject concreteSubject = new ConcreteSubject();
		concreteSubject.setSubjectState("I'm in good state");
		concreteSubject.attach(new ConcreteObserver(concreteSubject,"observer1"));
		concreteSubject.attach(new ConcreteObserver(concreteSubject,"observer2"));
		
		concreteSubject.notifyObservers();
	}

}


Java也提供了观察者模式的实现,java.util.Observable充当被观察者角色,一个具体的实现类。java.util.Observer充当观察者,一个接口,提供了update方法,不过Observable考虑了状态同步的问题,大家看源码便可知。


如若转载,请说明出处!http://blog.csdn.net/xukunddp

你可能感兴趣的:(Design,Pattern,设计模式,类)