观察者模式

观察者模式概述

观察者模式是对象的行为模式,又叫做发布-订阅模式、模型-视图模式、源-监听器模式或者从属者模式,这个模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使他们能够自动更新自己。

代码体现

由上面的描述,我们设想一个场景:在一个对象的值发生变化时没随即打印出变化后的这个值的二进制、八进制、十六进制表示法

package com.xnn;
/**
    *   类(接口)描述:观察者的抽象类  所有的观察者都需要继承他
 * @author xnn
 * 2018年11月5日下午3:47:25
 */
public abstract class Observer {
   protected Subject subject;
   public abstract void update();
}


package com.xnn;
import java.util.ArrayList;
import java.util.List;
/**
    *   类(接口)描述:这个是被观察的类
 * @author xnn
 * 2018年11月5日下午3:33:38
 */
public class 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 attach(Observer observer){
      observers.add(observer);      
   }
 /**
        *   唤醒所有的观察者
  * @author:xnn
  * 2018年11月5日下午3:35:31
  */
   public void notifyAllObservers(){
      for (Observer observer : observers) {
    	  //观察者所做的一些动作
         observer.update();
      }
   }  
}


package com.xnn;
/**
 * 
    *   类(接口)描述:二进制观察者 继承Observer 
 * @author xnn
 * 2018年11月5日下午3:39:27
 */
public class BinaryObserver extends Observer{
 //有参构造,参数是被观察的对象(Sucject)
   public BinaryObserver(Subject subject){
      this.subject = subject;
      //在实例化一个观察时,插入一个被观察的对象,并且把这个观察者对象加入到被观察者的观察者集合中去
      this.subject.attach(this);
   }
 
   @Override
   //当被观察者状态改变时,观察者会调用这个方法,做一些处理。
   public void update() {
      System.out.println( "Binary String: " 
      + Integer.toBinaryString( subject.getState() ) ); 
   }
}

package com.xnn;
/**
    *   类(接口)描述:八进制观察者 继承Observer 
 * @author xnn
 * 2018年11月5日15:45:13
 */
public class OctalObserver extends Observer{
	 //有参构造,参数是被观察的对象(Sucject)
   public OctalObserver(Subject subject){
      this.subject = subject;
      //在实例化一个观察时,插入一个被观察的对象,并且把这个观察者对象加入到被观察者的观察者集合中去
      this.subject.attach(this);
   }
 
   @Override   
   //当被观察者状态改变时,观察者会调用这个方法,做一些处理。
   public void update() {
     System.out.println( "Octal String: " 
     + Integer.toOctalString( subject.getState() ) ); 
   }
}

package com.xnn;
/**
    *   类(接口)描述:十六进制观察者 继承Observer 
 * @author xnn
 * 2018年11月5日下午3:46:04
 */
public class HexaObserver extends Observer{
	 //有参构造,参数是被观察的对象(Sucject)
   public HexaObserver(Subject subject){
      this.subject = subject;
      //在实例化一个观察时,插入一个被观察的对象,并且把这个观察者对象加入到被观察者的观察者集合中去
      this.subject.attach(this);
   }
 
   @Override
   //当被观察者状态改变时,观察者会调用这个方法,做一些处理。
   public void update() {
      System.out.println( "Hex String: " 
      + Integer.toHexString( subject.getState() ).toUpperCase() ); 
   }
}

package com.xnn;
/**
    *   类(接口)描述:主程序
 * @author xnn
 * 2018年11月5日下午3:48:28
 */
public class ObserverPatternDemo {
   public static void main(String[] args) {
	   //new一个内观察者的对象实例
      Subject subject = new Subject();
      
      //new观察者对象,并且把被观察者实例传进去
      new HexaObserver(subject);
      new OctalObserver(subject);
      new BinaryObserver(subject);
 
      System.out.println("First state change: 15");   
      //被观察者对象状态发生变化
      subject.setState(15);
      
      System.out.println("Second state change: 10");  
      subject.setState(10);
   }
}

上述例子所画出来的类图:

运行结果:

First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010

这个模式里面的角色

由上述例子。我们可以看出观察者模式中有如下几个角色:
1、抽象观察者角色(Observer):为所有的具体观察者定义一个接口,在得到主题的通知时更新自己。他一般用一个抽象类和一个接口实现,在本例中Observer就是一个抽象类,他只有一个update()方法,这个方法叫做更新方法;
2、主题角色(Subject):将有关状态存入具体观察者对象,在主题的内部状态发生改变时,给所有注册过的观察者发出通知;
3、具体观察者角色(即本例中的HexaObserver、OctalObserver、BinaryObserver):这个角色实现抽象观察者角色所要求的的更新接口,以便是本身的状态与主题的状态相协调

总结

由上面的例子可以总结出以下几点:

模式意图

定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

模式主要解决

一个对象状态改变给其他对象通知的问题,而且要考虑到易用和低耦合,保证高度的协作。

模式何时被使用

一个对象(目标对象)的状态发生改变,所有的依赖对象(观察者对象)都将得到通知,进行广播通知。

模式如何实现

使用面向对象技术,可以将这种依赖关系弱化。

模式的关键代码

在抽象类里有一个 ArrayList 存放观察者们。

模式的优点:

1、观察者和被观察者是抽象耦合的;
2、建立一套触发机制。

模式的缺点

1、如果一个被观察者对象有很多的直接和间接的观察者的话,将所有的观察者都通知到会花费很多时间;
2、如果在观察者和观察目标之间有循环依赖的话,观察目标会触发它们之间进行循环调用,可能导致系统崩溃;
3、观察者模式没有相应的机制让观察者知道所观察的目标对象是怎么发生变化的,而仅仅只是知道观察目标发生了变化。

使用该模式的注意事项

1、JAVA 中已经有了对观察者模式的支持类;(Observable类 Observer接口)
2、避免循环引用;
3、如果顺序执行,某一观察者错误会导致系统卡壳,一般采用异步方式。

JDK对观察者模式的支持

package com.xnn;
/**
 * 文章实体类
    *   类(接口)描述:
 * @author xnn
 * 2018年11月5日下午4:33:02
 */
public class Article {
	private String articleTitle;
	private String articleContent;

	public String getArticleTitle() {
		return articleTitle;
	}

	public void setArticleTitle(String articleTitle) {
		this.articleTitle = articleTitle;
	}

	public String getArticleContent() {
		return articleContent;
	}

	public void setArticleContent(String articleContent) {
		this.articleContent = articleContent;
	}

}

package com.xnn;

import java.util.Observable;
/**
    * 博客用户类,继承Observable(可被观察)类
    *   类(接口)描述:
 * @author xnn
 * 2018年11月5日下午4:33:32
 */

public class BlogUser extends Observable {
	
	public void publishBlog(String articleTitle,String articleContent) {
		Article art = new Article();
		art.setArticleTitle(articleTitle);
		art.setArticleContent(articleContent);
		System.out.println("博主:发表新文章,文章标题:" + articleTitle + ",文章内容:" + articleContent);
		  //状态发生改变 调用的是Observable类里面的方法 
		  /*protected synchronized void setChanged() {
            changed = true;
          }*/
		this.setChanged();
		//唤醒所有观察者
		this.notifyObservers(art);
	}
}


package com.xnn;

import java.util.Observable;
import java.util.Observer;
/**
 * 观察者类  实现Observer接口
    *   类(接口)描述:
 * @author xnn
 * 2018年11月5日下午4:56:51
 */
public class MyObServer implements Observer {
       //更新方法
	public void update(Observable o, Object arg) {
		Article art = (Article)arg;
		
		System.out.println("博主发表了新的文章,快去看吧!");
		System.out.println("博客标题为:" + art.getArticleTitle());
		System.out.println("博客内容为:" + art.getArticleContent());
	}

}


package com.xnn;

public class MainClass {
	public static void main(String[] args) {
		BlogUser user = new BlogUser();
		user.addObserver(new MyObServer());
		user.publishBlog("哈哈,博客上线了", "大家多来访问");
	}
}

运行结果:

博主:发表新文章,文章标题:哈哈,博客上线了,文章内容:大家多来访问
博主发表了新的文章,快去看吧!
博客标题为:哈哈,博客上线了
博客内容为:大家多来访问

附上 JDK源码

/*
 * Copyright (c) 1994, 1998, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package java.util;

/**
 * A class can implement the <code>Observer</code> interface when it
 * wants to be informed of changes in observable objects.
 *
 * @author  Chris Warth
 * @see     java.util.Observable
 * @since   JDK1.0
 */
public interface Observer {
    /**
     * This method is called whenever the observed object is changed. An
     * application calls an <tt>Observable</tt> object's
     * <code>notifyObservers</code> method to have all the object's
     * observers notified of the change.
     *
     * @param   o     the observable object.
     * @param   arg   an argument passed to the <code>notifyObservers</code>
     *                 method.
     */
    void update(Observable o, Object arg);
}


/*
 * Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
/
package java.util;

/**
 * This class represents an observable object, or "data"
 * in the model-view paradigm. It can be subclassed to represent an
 * object that the application wants to have observed.
 * <p>
 * An observable object can have one or more observers. An observer
 * may be any object that implements interface <tt>Observer</tt>. After an
 * observable instance changes, an application calling the
 * <code>Observable</code>'s <code>notifyObservers</code> method
 * causes all of its observers to be notified of the change by a call
 * to their <code>update</code> method.
 * <p>
 * The order in which notifications will be delivered is unspecified.
 * The default implementation provided in the Observable class will
 * notify Observers in the order in which they registered interest, but
 * subclasses may change this order, use no guaranteed order, deliver
 * notifications on separate threads, or may guarantee that their
 * subclass follows this order, as they choose.
 * <p>
 * Note that this notification mechanism is has nothing to do with threads
 * and is completely separate from the <tt>wait</tt> and <tt>notify</tt>
 * mechanism of class <tt>Object</tt>.
 * <p>
 * When an observable object is newly created, its set of observers is
 * empty. Two observers are considered the same if and only if the
 * <tt>equals</tt> method returns true for them.
 *
 * @author  Chris Warth
 * @see     java.util.Observable#notifyObservers()
 * @see     java.util.Observable#notifyObservers(java.lang.Object)
 * @see     java.util.Observer
 * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
 * @since   JDK1.0
 */
public class Observable {
    private boolean changed = false;
    private Vector obs;

    /** Construct an Observable with zero Observers. */

    public Observable() {
        obs = new Vector();
    }

    /**
     * Adds an observer to the set of observers for this object, provided
     * that it is not the same as some observer already in the set.
     * The order in which notifications will be delivered to multiple
     * observers is not specified. See the class comment.
     *
     * @param   o   an observer to be added.
     * @throws NullPointerException   if the parameter o is null.
     */
    public synchronized void addObserver(Observer o) {
        if (o == null)
            throw new NullPointerException();
        if (!obs.contains(o)) {
            obs.addElement(o);
        }
    }

    /**
     * Deletes an observer from the set of observers of this object.
     * Passing <CODE>null</CODE> to this method will have no effect.
     * @param   o   the observer to be deleted.
     */
    public synchronized void deleteObserver(Observer o) {
        obs.removeElement(o);
    }

    /**
     * If this object has changed, as indicated by the
     * <code>hasChanged</code> method, then notify all of its observers
     * and then call the <code>clearChanged</code> method to
     * indicate that this object has no longer changed.
     * <p>
     * Each observer has its <code>update</code> method called with two
     * arguments: this observable object and <code>null</code>. In other
     * words, this method is equivalent to:
     * <blockquote><tt>
     * notifyObservers(null)</tt></blockquote>
     *
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#hasChanged()
     * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    public void notifyObservers() {
        notifyObservers(null);
    }

    /**
     * If this object has changed, as indicated by the
     * <code>hasChanged</code> method, then notify all of its observers
     * and then call the <code>clearChanged</code> method to indicate
     * that this object has no longer changed.
     * <p>
     * Each observer has its <code>update</code> method called with two
     * arguments: this observable object and the <code>arg</code> argument.
     *
     * @param   arg   any object.
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#hasChanged()
     * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    public void notifyObservers(Object arg) {
        /*
         * a temporary array buffer, used as a snapshot of the state of
         * current Observers.
         */
        Object[] arrLocal;

        synchronized (this) {
            /* We don't want the Observer doing callbacks into
             * arbitrary code while holding its own Monitor.
             * The code where we extract each Observable from
             * the Vector and store the state of the Observer
             * needs synchronization, but notifying observers
             * does not (should not).  The worst result of any
             * potential race-condition here is that:
             * 1) a newly-added Observer will miss a
             *   notification in progress
             * 2) a recently unregistered Observer will be
             *   wrongly notified when it doesn't care
             */
            if (!changed)
                return;
            arrLocal = obs.toArray();
            clearChanged();
        }

        for (int i = arrLocal.length-1; i>=0; i--)
            ((Observer)arrLocal[i]).update(this, arg);
    }

    /**
     * Clears the observer list so that this object no longer has any observers.
     */
    public synchronized void deleteObservers() {
        obs.removeAllElements();
    }

    /**
     * Marks this <tt>Observable</tt> object as having been changed; the
     * <tt>hasChanged</tt> method will now return <tt>true</tt>.
     */
    protected synchronized void setChanged() {
        changed = true;
    }

    /**
     * Indicates that this object has no longer changed, or that it has
     * already notified all of its observers of its most recent change,
     * so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
     * This method is called automatically by the
     * <code>notifyObservers</code> methods.
     *
     * @see     java.util.Observable#notifyObservers()
     * @see     java.util.Observable#notifyObservers(java.lang.Object)
     */
    protected synchronized void clearChanged() {
        changed = false;
    }

    /**
     * Tests if this object has changed.
     *
     * @return  <code>true</code> if and only if the <code>setChanged</code>
     *          method has been called more recently than the
     *          <code>clearChanged</code> method on this object;
     *          <code>false</code> otherwise.
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#setChanged()
     */
    public synchronized boolean hasChanged() {
        return changed;
    }

    /**
     * Returns the number of observers of this <tt>Observable</tt> object.
     *
     * @return  the number of observers of this object.
     */
    public synchronized int countObservers() {
        return obs.size();
    }
}


原文地址:https://www.cnblogs.com/nnxud/p/9906564.html