簡單的觀察者模式實現
代碼如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* 觀察者模式中用到了回調:
* A. 觀察者將自己注冊到被觀察者的監聽者列表,且觀察者類自身提供了一個回調函數
* B. 被觀察者(Observable或Subject)維護觀察者列表,並且可以注冊和解注冊觀察者
* C. 一旦被觀察者狀態發生改變,它可以調用notifyObservers(),這個方法將遍歷觀察者列表並逐個調用
觀察者提供的回調函數
* @author will
*
*/
public class SimpleObserverPattern {
public static void main(String[] args) {
SimpleObserverPattern sop = new SimpleObserverPattern();
List<IObserver> observers = new ArrayList<IObserver> ();
IObserver observerA = sop.new Observer("ObserverA");
IObserver observerB = sop.new Observer("ObserverB");
observers.add(observerA);
observers.add(observerB);
IObservable observable = sop.new Observable(observers);
observable.registerObserver(sop.new Observer("ObserverC"));
observable.changeState();
observable.close();
}
// 被觀察者,有的地方叫Subject
interface IObservable {
void registerObserver(IObserver observer);
void unregisterObserver(IObserver observer);
void notifyObservers();
String getState();
void changeState();
void close();
}
class Observable implements IObservable {
private static final String NEW = "New";
private static final String CHANGED = "Changed";
private static final String CLOSED = "Closed";
private String state;
private List<IObserver> observers;
public Observable() {
this(null);
}
public Observable(List<IObserver> observers) {
if(observers == null) {
observers = new ArrayList<IObserver> ();
}
this.observers = Collections.synchronizedList(observers);
this.state = NEW;
}
@Override
public void registerObserver(IObserver observer) {
observers.add(observer);
}
@Override
public void unregisterObserver(IObserver observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
Iterator<IObserver> iter = observers.iterator();
while(iter.hasNext()) {
iter.next().update(this);
}
}
@Override
public String getState() {
return state;
}
@Override
public void changeState() {
this.state = CHANGED;
notifyObservers();
}
@Override
public void close() {
this.state = CLOSED;
notifyObservers();
}
}
interface IObserver {
void update(IObservable observalbe);
}
class Observer implements IObserver {
private String name;
public Observer(String name) {
this.name = name;
}
@Override
public void update(IObservable observalbe) {
System.out.println(
String.format("%s receive observalbe's change, current observalbe's state is %s",
name, observalbe.getState()));
}
}
}
上面的實現直接將被觀察者對象作為回調函數參數,這樣做很不優雅,在簡單的場景可能奏效。
但事實上更多情況下,一個被觀察者有很多種事件或者狀態,而每個觀察者可能感興趣的事件或狀態都不相同,或者為了信息隱藏的目的,不想讓每個觀察者都能訪問到Observable內部的所有狀態。
這樣我繼續演化代碼為下面這個版本,注意我這裡沒有很細致地考慮並發問題。
代碼如下:
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class MultiEventObserverPattern {
public static void main(String[] args) {
MultiEventObserverPattern meop = new MultiEventObserverPattern();
IObservable observable = meop.new Observable();
IObserver observerA = meop.new Observer("ObserverA");
IObserver observerB = meop.new Observer("ObserverB");
// 注冊感興趣的事件
observable.registerObserver(observable.getEventA(), observerA);
observable.registerObserver(observable.getEventB(), observerB);
// 改變被觀察者狀態
observable.changeStateA();
observable.changeStateB();
}
interface IEvent {
void eventChange();
String getState();
}
class EventA implements IEvent {
private static final String INITIALIZED = "Initialized";
private static final String PENDING = "Pending";
private String state;
public EventA() {
this.state = INITIALIZED;
}
@Override
public void eventChange() {
System.out.println("EventA change");
this.state = PENDING;
}
@Override
public String toString() {
return "EventA";
}
@Override
public String getState() {
return state;
}
}
class EventB implements IEvent {
private static final String NEW = "New";
private static final String IDLE = "Idle";
private String state;
public EventB() {
this.state = NEW;
}
@Override
public void eventChange() {
System.out.println("EventB change");
this.state = IDLE;
}
@Override
public String toString() {
return "EventB";
}
@Override
public String getState() {
return state;
}
}
// 被觀察者(Observable),有的地方叫Subject
interface IObservable {
void registerObserver(IEvent event, IObserver observer);
void unregisterObserver(IEvent event, IObserver observer);
// 通知觀察者某個事件發生了
void notifyObservers(IEvent event);
void changeStateA();
void changeStateB();
IEvent getEventA();
IEvent getEventB();
}
class Observable implements IObservable {
private IEvent eventA;
private IEvent eventB;
private Hashtable<IEvent, Set<IObserver>> eventObserverMapping;
public Observable() {
this(null);
}
// 這裡如果evenObserverMapping傳入的某些Set<IObserver>是未被同步修飾的,那麼也沒辦法
public Observable(Hashtable<IEvent, Set<IObserver>> eventObserverMapping) {
if(eventObserverMapping == null) {
eventObserverMapping = new Hashtable<IEvent, Set<IObserver>> ();
}
this.eventObserverMapping = new Hashtable<IEvent, Set<IObserver>> ();
this.eventA = new EventA();
this.eventB = new EventB();
}
@Override
public void registerObserver(IEvent event, IObserver observer) {
Set<IObserver> observers = eventObserverMapping.get(event);
if(observers == null) {
observers = Collections.synchronizedSet(new HashSet<IObserver> ());
observers.add(observer);
eventObserverMapping.put(event, observers);
}
else {
observers.add(observer);
}
}
@Override
public void unregisterObserver(IEvent event, IObserver observer) {
Set<IObserver> observers = eventObserverMapping.get(event);
if(observers != null) {
observers.remove(observer);
}
}
@Override
public void notifyObservers(IEvent event) {
Set<IObserver> observers = eventObserverMapping.get(event);
if(observers != null && observers.size() > 0) {
Iterator<IObserver> iter = observers.iterator();
while(iter.hasNext()) {
iter.next().update(event);
}
}
}
@Override
public void changeStateA() {
// 改變狀態A會觸發事件A
eventA.eventChange();
notifyObservers(eventA);
}
@Override
public void changeStateB() {
// 改變狀態B會觸發事件B
eventB.eventChange();
notifyObservers(eventB);
}
@Override
public IEvent getEventA() {
return eventA;
}
@Override
public IEvent getEventB() {
return eventB;
}
}
interface IObserver {
void update(IEvent event);
}
class Observer implements IObserver {
private String name;
public Observer(String name) {
this.name = name;
}
@Override
public void update(IEvent event) {
System.out.println(
String.format("%s receive %s's change, current observalbe's state is %s",
name, event, event.getState()));
}
}
}
似乎看起來挺完美了,但還是不夠完美。因為事件被硬編碼為被觀察者類的屬性。這樣事件類型在編譯時期就被定死了,如果要增加新的事件類型就不得不修改IObservable接口和Observable類,這大大削減了靈活性。
相當於被觀察者耦合於這些具體的事件,那麼我們如何來打破這個限制呢?
答案是引入一個新的組件,讓那個組件來管理事件、觀察者、被觀察者之間的關系,事件發生時也由那個組件來調用觀察者的回調函數。這也是一種解耦吧,有點類似Spring的IOC容器。
至於具體實現,我覺得Guava EventBus做得已經蠻好了,可以參考我前面提到的鏈接。
PS:本帖不是為Guava EventBus做廣告,只是自己的思路一步步推進,逐漸地就和Guava EventBus的設計思路吻合了。
下面繼續看看JDK標准類實現觀察者模式的例子,然後分析下它的源碼實現,要看的只有一個Observable類和一個Observer接口。
JDK標准類實現觀察者模式
代碼如下:
import java.util.Observable;
import java.util.Observer;
/**
* 使用java.util包中的標准類實現觀察者模式
* @author will
*
*/
public class JDKObserverDemo {
public static void main(String[] args) {
JDKObserverDemo jod = new JDKObserverDemo();
// 被觀察者
MyObservable myObservable = jod.new MyObservable("hello");
// 觀察者
Observer myObserver = jod.new MyObserver();
// 注冊
myObservable.addObserver(myObserver);
// 改變被觀察者狀態,觸發觀察者回調函數
myObservable.setValue("will");
}
class MyObservable extends Observable {
private String watchedValue; // 被觀察的值
public MyObservable(String watchedValue) {
this.watchedValue = watchedValue;
}
public void setValue(String newValue) {
if(!watchedValue.equals(newValue)) {
watchedValue = newValue;
setChanged();
notifyObservers(newValue);
}
}
@Override
public String toString() {
return "MyObservable";
}
}
class MyObserver implements Observer {
@Override
public void update(Observable o, Object arg) {
System.out.println(o + "'s state changed, argument is: " + arg);
}
}
}
看了下JDK標准庫中的Observer和Observable實現很簡單,不想多說了。
下面是Quartz中的監聽器實現。
QuartzScheduler被監聽者
代碼如下:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Quartz核心類,相當於Observable(被觀察者)
* @author will
*
*/
public class QuartzScheduler {
private ArrayList<SchedulerListener> internalSchedulerListeners = new ArrayList<SchedulerListener>(10);
// private ArrayList<JobListener> interanlJobListeners = new ArrayList<JobListener>(); // 一個Observable可以包含多組監聽器
public Date scheduleJob(Trigger trigger) {
if(trigger == null) {
return null;
}
System.out.println("Schedule job, trigger: " + trigger);
notifySchedulerListenersScheduled(trigger);
return new Date();
}
public void unScheduleJob(Trigger trigger) {
if(trigger == null) {
return;
}
System.out.println("Unschedule job, trigger: " + trigger);
notifyShedulerListenerUnScheduled(trigger);
}
// 注冊SchedulerListener
public void addInternalSchedulerListener(SchedulerListener schedulerListener) {
synchronized (internalSchedulerListeners) {
internalSchedulerListeners.add(schedulerListener);
}
}
// 移除SchedulerListener
public boolean removeInternalSchedulerListener(SchedulerListener schedulerListener) {
synchronized (internalSchedulerListeners) {
return internalSchedulerListeners.remove(schedulerListener);
}
}
public List<SchedulerListener> getInternalSchedulerListeners() {
synchronized (internalSchedulerListeners) {
return java.util.Collections.unmodifiableList(new ArrayList<SchedulerListener>(internalSchedulerListeners));
}
}
public void notifySchedulerListenersScheduled(Trigger trigger) {
for(SchedulerListener listener: getInternalSchedulerListeners()) {
listener.jobScheduled(trigger);
}
}
public void notifyShedulerListenerUnScheduled(Trigger trigger) {
for(SchedulerListener listener: getInternalSchedulerListeners()) {
listener.jobUnScheduled(trigger);
}
}
}
SchedulerListener
代碼如下:
// 監聽接口,回調函數,Client注冊監聽時需要提供回調函數實現
public interface SchedulerListener {
void jobScheduled(Trigger trigger);
void jobUnScheduled(Trigger trigger);
}
Trigger
代碼如下:
// Trigger
public class Trigger {
private String triggerKey;
private String triggerName;
public Trigger(String triggerKey, String triggerName) {
this.triggerKey = triggerKey;
this.triggerName = triggerName;
}
public String getTriggerKey() {
return triggerKey;
}
public void setTriggerKey(String triggerKey) {
this.triggerKey = triggerKey;
}
public String getTriggerName() {
return triggerName;
}
public void setTriggerName(String triggerName) {
this.triggerName = triggerName;
}
public String toString() {
return String.format("{triggerKey: %s, triggerName: %s}", triggerKey, triggerName);
}
}
Test
代碼如下:
public class Test {
public static void main(String[] args) {
QuartzScheduler qs = new QuartzScheduler();
SchedulerListener listenerA = new SchedulerListener() {
@Override
public void jobUnScheduled(Trigger trigger) {
System.out.println("listenerA job unscheduled: " + trigger.getTriggerName());
}
@Override
public void jobScheduled(Trigger trigger) {
System.out.println("listenerA job scheduled: " + trigger.getTriggerName());
}
};
SchedulerListener listenerB = new SchedulerListener() {
@Override
public void jobUnScheduled(Trigger trigger) {
System.out.println("listenerB job unscheduled: " + trigger.getTriggerName());
}
@Override
public void jobScheduled(Trigger trigger) {
System.out.println("listenerB job scheduled: " + trigger.getTriggerName());
}
};
// 注冊Scheduler Listener
qs.addInternalSchedulerListener(listenerA);
qs.addInternalSchedulerListener(listenerB);
Trigger triggerA = new Trigger("Key1", "triggerA");
Trigger triggerB = new Trigger("Key2", "triggerB");
qs.scheduleJob(triggerA);
qs.scheduleJob(triggerB);
qs.unScheduleJob(triggerA);
}
}