观察者模式(Observer Pattern)

观察者模式定义了一系列对象之间的一对多关系。当一个对象改变状态, 其他依赖者都会收到通知。 -《HeadFisrt设计模式》

1. 举个例子

/* 观察的主题 */

public class Subject {

    private List observers;

    public void init() {
        observers = new ArrayList();
        observers.add(new Observer1());
        observers.add(new Observer2());
        observers.add(new Observer3());
    }

    public void somethingChanged() {
        for (Observer observer : observers) {
            observer.react();
        }
    }

    public static void main(String[] args) {
        Subject subject = new Subject();
        subject.init();
        subject.somethingChanged();
    }
}
/* 观察者 */

public interface Observer {

    void react();
}

public class Observer1 implements Observer {

    public void react() {
        System.out.println("Observer1 receive message from subject.");
    }
}

public class Observer2 implements Observer {

    public void react() {
        System.out.println("Observer2 receive message from subject.");
    }
}

public class Observer3 implements Observer {

    public void react() {
        System.out.println("Observer3 receive message from subject.");
    }
}

2. 开闭原则

上面的代码并不是真正观察者模式,因为违反了面向对象设计中最基础的设计原则。

软件实体(类,模块,方法等等)应当对扩展开放,对修改关闭,即软件实体应当在不修改的前提下扩展。 - 开闭原则(Open-Close Principle)

每新增一个观察者就需要在Subject类中调用一次observers.add,并不是对修改关闭。

3. 真正的观察者模式

/* 观察的主题 */

public class Subject {

    private List observers;

    public void init() {
        observers = new ArrayList();
    }

    public void somethingChanged() {
        for (Observer observer : observers) {
            observer.react();
        }
    }

    public void register(Observer observer) {
        observers.add(observer);
    }

    public static void main(String[] args) {
        Subject subject = new Subject();
        subject.init();

        Observer observer1 = new Observer1();
        observer1.listen(subject);

        Observer observer2 = new Observer1();
        observer2.listen(subject);

        Observer observer3 = new Observer1();
        observer3.listen(subject);

        subject.somethingChanged();
    }
}
/* 观察者 */

public interface Observer {

    void react();

    void listen(Subject subject);
}

public class Observer1 implements Observer {

    public void react() {
        System.out.println("Observer1 receive message from subject.");
    }

    public void listen(Subject subject) {
        subject.register(this);
    }
}

public class Observer2 implements Observer {

    public void react() {
        System.out.println("Observer2 receive message from subject.");
    }

    public void listen(Subject subject) {
        subject.register(this);
    }
}

public class Observer3 implements Observer {

    public void react() {
        System.out.println("Observer3 receive message from subject.");
    }

    public void listen(Subject subject) {
        subject.register(this);
    }
}

4. JDK自带的观察者

/* 观察的主题 */

import java.util.Observable;

public class Subject extends Observable {

    public static void main(String[] args) {
        Subject subject = new Subject();

        Observer1 observer1 = new Observer1();
        subject.addObserver(observer1);

        Observer2 observer2 = new Observer2();
        subject.addObserver(observer2);

        Observer3 observer3 = new Observer3();
        subject.addObserver(observer3);

        subject.setChanged();
        subject.notifyObservers();
    }
}
/* 观察者 */

import java.util.Observable;
import java.util.Observer;

public class Observer1 implements Observer {

    public void update(Observable o, Object arg) {
        System.out.println("Observer1 receive message from subject.");
    }
}

public class Observer2 implements Observer {

    public void react() {
        System.out.println("Observer2 receive message from subject.");
    }
}

public class Observer3 implements Observer {

    public void update(Observable o, Object arg) {
        System.out.println("Observer3 receive message from subject.");
    }
}

5. 注意事项

  1. JDK中的被观察对象在获取观察者时是同步的,但是执行通知事件时却不是。
package java.util;

public class Observable {

    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);
    }

}
  1. 如果顺序执行通知,某一观察者错误会导致系统卡壳,一般采用异步方式。

你可能感兴趣的:(观察者模式(Observer Pattern))