Chapter 14 观察者模式
观察者模式又叫做发布-订阅模式:定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
观察者模式所做的工作其实就是在解除耦合,让耦合的双方都依赖于抽象,而不是依赖于具体,从而使得各自的变化都不会影响另一边的变化。
代码如下:
package xiao;
import java.util.ArrayList;
import java.util.List;
interface Subject{
void Attach(Observer observer);
void Detach(Observer observer);
void Notify();
String getSubjectState();
void setSubjectState(String subjectState);
}
abstract class Observer{
protected String name;
protected Secretary sub;
public abstract void update();
}
class Secretary implements Subject{
private List<Observer> observers = new ArrayList<Observer>();
private String subjectState;
public void Attach(Observer observer){
observers.add(observer);
}
public void Detach(Observer observer){
observers.remove(observer);
}
public void Notify(){
for(Observer o:observers){
o.update();
}
}
public String getSubjectState() {
return subjectState;
}
@Override
public void setSubjectState(String subjectState) {
this.subjectState = subjectState;
}
}
class StockObserver extends Observer
{
public StockObserver(String name,Secretary sub){
this.name = name;
this.sub = sub;
}
public void update(){
System.out.println(sub.getSubjectState()+this.name+"关闭股票,继续工作");
}
}
class NBAObserver extends Observer
{
public NBAObserver(String name,Secretary sub){
this.name = name;
this.sub = sub;
}
public void update(){
System.out.println(sub.getSubjectState()+this.name+"关闭NBA,继续工作");
}
}
public class abc {
public static void main(String[] args) {
Secretary tongzizhe = new Secretary();
StockObserver tongshi1 = new StockObserver("mike", tongzizhe);
NBAObserver tongshi2 = new NBAObserver("dave", tongzizhe);
tongzizhe.Attach(tongshi2);
tongzizhe.Attach(tongshi1);
tongzizhe.setSubjectState("boss is coming ");
tongzizhe.Notify();
}
}