zoukankan      html  css  js  c++  java
  • 观察者模式(Observer Pattern)

    观察者模式:定义了对象之间的一对多依赖,这样依赖,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。

    下面举一个具体例子:

    两个观察者,BinaryObserver的update将setState传入的整数转换成二进制,OctaObserver则是转成八进制

    interface Subject {
        
       private List<Observer> observers;
    
        public void registerObserver(Observer o);
    
        public void removeObserver(Observer o);  
    
       public void notifyAllObservers();
    }
    public class ConcreteSubject implements Subject{
        
       private List<Observer> observers 
          = new ArrayList<Observer>();
       private int state;
    
       public int getState() {
          return state;
       }
    
       public void setState(int state) {
          this.state = state;
          notifyAllObservers();
       }
    
       public void registerObserver(Observer observer){
          observers.add(observer);        
       }
    
        public void removeObserver(Observer observer){
           int i = observers.indexOf(observer);
           if(i >= 0)
                  observers.remove(i);
        }
    
       public void notifyAllObservers(){
          for (Observer observer : observers) {
             observer.update();
          }
       }     
    }
    abstract Observer {
       public abstract void update();
    }
     
    public class BinaryObserver implements Observer{
      Subject subject;
       public BinaryObserver(Subject subject){
          this.subject = subject;
          this.subject.attach(this);
       }
    
       @Override
       public void update() {
          System.out.println( "Binary String: " 
          + Integer.toBinaryString( subject.getState() ) ); 
       }
    }
    public class OctalObserver implements Observer{
       Subject subject;
       public OctalObserver(Subject subject){
          this.subject = subject;
          this.subject.attach(this);
       }
    
       @Override
       public void update() {
         System.out.println( "Octal String: " 
         + Integer.toOctalString( subject.getState() ) ); 
       }
    }

    测试代码:

    Subject subject = new ConcreteSubject();
    Observer o = new OctalObserver(subject);
    Observer b = new BinaryObserver(subject);
    
    subject.registerObserver(o);
    subject.registerObserver(b); subject.setState(
    15); subject.setState(10);

    在Swing中有使用到观察者模式,比如JButton的addActionListener方法。

  • 相关阅读:
    ps4 如何导出切片 单个图片
    测试webservice的时候,如果出现这个错误:"The test form is only available for requests from the local machine"
    js jquery 按钮点击后 60秒之后才能点击 60秒倒计时
    有空研究一下 superwebsocket (底层是 supersocket) 用来实现 web聊天什么的
    Vue学习笔记一:初识Vue
    被爬虫了,嘻嘻嘻
    Mybatis-generator自动生成器
    SpringCloud笔记五:Feign
    SpringCloud笔记四:Ribbon
    SpringCloud笔记三:Eureka服务注册与发现
  • 原文地址:https://www.cnblogs.com/13jhzeng/p/5548154.html
Copyright © 2011-2022 走看看