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方法。

  • 相关阅读:
    c语言学习笔记(6)——for和while循环
    c语言学习笔记(5)——进制
    c语言学习笔记(4)——流程控制
    ckeditor复制粘贴word
    java上传超大文件
    plupload上传整个文件夹
    vue+上传文件夹
    php+上传大文件
    web+文件夹上传
    2G以上的大文件如何上传
  • 原文地址:https://www.cnblogs.com/13jhzeng/p/5548154.html
Copyright © 2011-2022 走看看