观察者模式

观察者模式:定义对象的一对多依赖关系,使得每当一个对象状态更改都会通知关联对象进行自动更新

优点:建立触发机制,观察者和被观察者分离,调用者不用关心具体的观察者行为

 

标准类图:


观察者模式
 抽象主题:

public abstract class Subject {
	
	private List<Observer> observers = new ArrayList<>();
	
	public void addObserver(Observer observer){
		this.observers.add(observer);
	}
	
	public void notifyObservers(String message){
		for (Observer observer : observers) {
			observer.update(this, message);
		}
	}
	
	
}

 具体主题:

public class ConcreteSubject extends Subject {
	
	private String name;
	
	public ConcreteSubject(){
		
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		super.notifyObservers(name);
		this.name = name;
	}

}

 抽闲观察者:

public interface Observer {
	
	public void update(Subject subject, String message);
	
}

 具体观察者:

public class ConcreteObserver implements Observer{

	@Override
	public void update(Subject subject, String message) {
		System.out.println(subject.toString());
		System.out.println(message);
	}
	
}

 场景类:

public class Client {
	
	public static void main(String[] args) {
		ConcreteSubject subject = new ConcreteSubject();
		Observer observer1 = new ConcreteObserver();
		Observer observer2 = new ConcreteObserver();
		Observer observer3 = new ConcreteObserver();
		subject.addObserver(observer1);
		subject.addObserver(observer2);
		subject.addObserver(observer3);
		subject.setName("robbie");
	}
	
}

 

你可能感兴趣的:(观察者模式)