Home > Java > javaTutorial > Java built-in observer pattern

Java built-in observer pattern

伊谢尔伦
Release: 2016-12-05 11:26:56
Original
1188 people have browsed it

I have briefly written a small example of the observer pattern (also known as the publish-subscribe pattern) before, and this pattern is also commonly used in projects now. Today I’ll post how to use Java’s built-in observer pattern.
The main Java APIs used are two classes:

Observer interface: Observer object, which monitors data changes of the observed object. Once the data changes, it will respond accordingly.

Observable class: Observable object, provides methods to add and remove observer objects, and notifies all added observer objects when the data is completed.
Observer code example:

//Observable是被观察者对象接口,实现该接口就是:目标(被观察者)的具体实现
public class TargetObservable extends Observable {
    // 要观察的数据:消息发生改变时,所有被添加的观察者都能收到通知
    private String message;    
      public String getConent() {        
        return message;
    }    
     public void setMessage(String message) {        
     this.message = message;        
     // 被观察者数据发生变化时,通过以下两行代码通知所有的观察者
        this.setChanged();        
        this.notifyObservers(message);
    }
}
Copy after login

2 observer code examples:

//Observer对象是观察者,实现Observer的对象就是具体的观察者对象
   public class TargetObserver implements Observer {
    // 定义观察者名称
    private String name;    
      public String getObserverName() {        
          return name;
    }    
          public void setObserverName(String observerName) {        
          this.name = observerName;
    }    
          @Override
    public void update(Observable arg0, Object arg1) {        
          //更新消息数据
        System.out.println(name + "收到了发生变化的数据内容是:"
                + ((TargetObservable) arg0).getConent());
    }
}
Copy after login
public class TargetObserver01 implements Observer {
    // 定义观察者名称
    private String name01;    
      public String getObserverName() {        
           return name01;
    }    
           public void setObserverName(String observerName) {        
           this.name01 = observerName;
    }    
           @Override
    public void update(Observable arg0, Object arg1) {        
           //更新消息数据
        System.out.println(name01 + "收到了发生变化的数据内容是:"
                + ((TargetObservable) arg0).getConent());
    }
}
Copy after login

Test code:

public static void main(String[] args) {        
// 创建一个具体的被 观察者
        TargetObservable observable = new TargetObservable();        
        // 创建第一个观察者
        TargetObserver one = new TargetObserver();
        one.setObserverName("我是观察者A");        
        // 创建第二个观察者
        TargetObserver01 two = new TargetObserver01();
        two.setObserverName("我是观察者B");        
        // 注册观察者
        observable.addObserver(one);
        observable.addObserver(two);        
        // 目标更新天气情况
        observable.setMessage("***我要更新的数据***");
    }

}
Copy after login

Execution result:
I am observer B and received the changed data content: —–I want to update Data————
I am an observer A. I have received the changed data. The content is:————The data I want to update————
Advantages of the mode:
One observer can correspond to multiple observers. When the observed changes At that time, he can notify the message to all added observers. Interface-based implementation provides greater flexibility for programs.
But when using it, be careful to add or remove observer objects in time according to conditions, otherwise it may lead to unexpected results.
Finally, attach the original code of Observer and Observable, so that we know how to start when writing:

package java.util;
import java.util.Observable;
public interface Observer {
    void update(Observable var1, Object var2);
}
Copy after login
package java.util;
import java.util.Observer;
import java.util.Vector;
public class Observable {
    private boolean changed = false;    
      private Vector<Observer> obs = new Vector();    
      public Observable() {
    }    
      public synchronized void addObserver(Observer var1) {        
      if(var1 == null) {            
      throw new NullPointerException();
        } else {            
             if(!this.obs.contains(var1)) {                
             this.obs.addElement(var1);
            }

        }
    }    
             public synchronized void deleteObserver(Observer var1) {        
                this.obs.removeElement(var1);
    }    
             public void notifyObservers() {        
                this.notifyObservers((Object)null);
    }      
             public void notifyObservers(Object var1) {
                Object[] var2;        
                    synchronized(this) {            
                       if(!this.changed) {                
                          return;
            }

            var2 = this.obs.toArray();            
                          this.clearChanged();
        }        
                  for(int var3 = var2.length - 1; var3 >= 0; --var3) {
              ((Observer)var2[var3]).update(this, var1);
        }

    }    
                  public synchronized void deleteObservers() {        
                  this.obs.removeAllElements();
    }    
                  protected synchronized void setChanged() {        
                  this.changed = true;
    }    
                  protected synchronized void clearChanged() {        
                  this.changed = false;
    }    
                  public synchronized boolean hasChanged() {        
                  return this.changed;
    }    
                  public synchronized int countObservers() {        
                  return this.obs.size();
    }
}
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template