设计模式之---观察者模式

in #steemit7 years ago


观察者模式

定义

Define a one-to-many dependency between objects so thatwhen one object changes state, all its dependents are notifiedand updated automatically.
定义对象间一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖于它的对象都会得到通知并被自动更新。
类图:略
从类图可以看到,观察者模式一般有这样几个类】

  • 被观察者 SUbject
  • 观察者 Observer
  • 具体的被观察者 ConcreteSubject
  • 具体的观察者 ConcreteObserver

优点

  • 观察者被观察者之间抽象耦合
  • 一对多的对应关系和触发机制

缺点

  • 触发机制如果选择不当,会影响效率
    实现代码
public  abstract class Subject {
    private Vector observers=new Vector();
 public void addObserver(Observer observer){
        this.observers.add(observer);
  }
    public void delObserver(Observer observer){
        this.observers.remove(observer);
  }
    public void notifyObservers(){
        for(Observer observer:observers){
            observer.update();
  }
    }
}
public interface Observer {
    public void update();
}
public class ConcreteSubject extends Subject {
    public void doSomething(){
        super.notifyObservers();
  }

}
public class ConcreteObserver implements Observer {
    public void update() {
        System.out.println("收到通知,更新完成");
  }
}

测试类

public class Test {
    public static void main(String[] args) {
        ConcreteSubject subject=new ConcreteSubject();
  Observer observer=new ConcreteObserver();
  subject.addObserver(observer);
  subject.doSomething();
  }
}

运行结果

收到通知,更新完成

使用场景

  • 一对多的触发事件
  • 系统间图通信,如消息队列
  • 广播
Sort:  

Congratulations @hiquanta! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the total payout received

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!