观察者模式(Observer Pattern),用于当一对象发生改变时,能自动通知到其他依赖的对象,类似于监听机制。该模式属于行为型模式。打个现实中的例子,就比如博客主题的订阅功能,当订阅了某主题之后,该主题发布新内容会通知到所有的订阅者账号上,这其实就是一种观察者模式的应用。
上面博客主题订阅的例子中,订阅者在观察者模式中就称之为观察者对象,而主题就属于是目标对象。当目标对象做出了修改,它的所有观察者就会得到相应的内容通知。
接下来用代码实现一下这个功能。
IObserver观察者接口类有个update的通知接收方法和一个show内容展示方法,update方法的参数为Subject目标对象,从中取得目标对象的通知内容。
package com.minant.observer;
/**
* @ClassName IObserver
* @Description TODO 抽象观察者
* @Author MinAnt
* @Date 2020/5/29
* @Version V1.0
*/
public interface IObserver {
void update(Subject subject);
void show();
}
Subject类为目标对象的基类,其中用Arraylist维护了目标对象的所有观察者对象,其中还有观察者注册方法regist、观察者删除方法remove以及通知所有观察者的方法notifyAllobs。
package com.minant.observer;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName Subject
* @Description TODO 目标对象
* @Author MinAnt
* @Date 2020/5/29
* @Version V1.0
*/
public class Subject {
protected List<IObserver> observerList = new ArrayList<>();
public void regist(IObserver observer) {
observerList.add(observer);
}
public void remove(IObserver observer) {
observerList.remove(observer);
}
public void notifyAllobs() {
for (IObserver observer: observerList) {
observer.update(this);
}
}
}
MyObserver是IObserver观察者实现类,有一个名称属性name和一个通知内容属性msg。
package com.minant.observer;
/**
* @ClassName MyObserver
* @Description TODO 具体观察者
* @Author MinAnt
* @Date 2020/5/29
* @Version V1.0
*/
public class MyObserver implements IObserver {
private String name;
private String msg;
public MyObserver(String name) {
this.name = name;
}
@Override
public void update(Subject subject) {
msg = ((MySubject)subject).getNews();
this.show();
}
@Override
public void show() {
if(this.msg == null) {
System.out.println(name + "->没有任何通知!");
}
System.out.println(name + "->收到通知:" + this.msg);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
MySubject目标对象继承自Subject有一个消息属性news,在修改该属性的时候调用了父类的通知方法以及时将修改内容通知到各观察者。
package com.minant.observer;
/**
* @ClassName MySubject
* @Description TODO 具体目标对象
* @Author MinAnt
* @Date 2020/5/29
* @Version V1.0
*/
public class MySubject extends Subject {
private String news;
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
// 通知所有观察者
this.notifyAllobs();
}
}
测试类:
package com.minant.observer;
/**
* @ClassName TestObserver
* @Description TODO 测试观察者模式
* @Author MinAnt
* @Date 2020/5/29
* @Version V1.0
*/
public class TestObserver {
public static void main(String[] args) {
// 创建主题
MySubject sb = new MySubject();
// 创建观察者
MyObserver ob1 = new MyObserver("ob1");
MyObserver ob2 = new MyObserver("ob2");
MyObserver ob3 = new MyObserver("ob3");
MyObserver ob4 = new MyObserver("ob4");
// 注册观察者
sb.regist(ob1);
sb.regist(ob2);
sb.regist(ob3);
sb.regist(ob4);
// 修改内容,发布通知
sb.setNews("今天小雨转晴!");
}
}
测试结果:
以上就是观察者模式的原理。在实际开发中为了简化开发者的工作,其实JDK已经对该模式进行了一个封装了。
在java.util包下就有观察者接口java.util.Observer:
参数Observable其实和上面的Subject目标类原理是一样的,只是其中实现不同(有兴趣的自己翻看源码好了),它们都是目标类对象。还有个Object类形的参数就是其他参数对象,可以有其他内容。
Observable的源码这里也贴下:
/*
* Copyright (c) 1994, 2012, 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 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<Observer> 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();
}
}
用起来就方便很多了,和上面自己写的原理也是一样的:
定义个目标类:
package com.minant.observer.proto;
import java.util.Observable;
/**
* @ClassName SimpleSubject
* @Description TODO jdk自带-目标类
* @Author MinAnt
* @Date 2020/5/29
* @Version V1.0
*/
public class SimpleSubject extends Observable {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
setChanged();
super.notifyObservers(this);
// super.notifyObservers();
}
}
定义个观察者类:
package com.minant.observer.proto;
import java.util.Observable;
import java.util.Observer;
/**
* @ClassName SimpleObserver
* @Description TODO jdk自带-观察者
* @Author MinAnt
* @Date 2020/5/29
* @Version V1.0
*/
public class SimpleObserver implements Observer {
private String name;
private String msg;
public SimpleObserver(String name) {
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
msg = ((SimpleSubject) arg).getMsg();
// msg = ((SimpleSubject)o).getMsg();
this.show();
}
private void show() {
if(this.msg == null) {
System.out.println(name + "->没有任何通知!");
}
System.out.println(name + "->收到通知:" + this.msg);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
测试:
package com.minant.observer.proto;
/**
* @ClassName TestSimpleObserver
* @Description TODO 测试JDK观察者
* @Author MinAnt
* @Date 2020/5/29
* @Version V1.0
*/
public class TestSimpleObserver {
public static void main(String[] args) {
// 创建主题
SimpleSubject subject = new SimpleSubject();
// 创建观察者
SimpleObserver observer1 = new SimpleObserver("observer1");
SimpleObserver observer2 = new SimpleObserver("observer2");
SimpleObserver observer3 = new SimpleObserver("observer3");
// 注册
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.addObserver(observer3);
// 通知
subject.setMsg("今夜阳光明媚!");
}
}
得到结果:
一样儿一样儿的,如果没有什么特殊需求还是建议不要自己写了,用自带的便捷(人懒就是这么想的)。
以上就是观察者模式的内容。