设计模式-观察者模式

首先了解观察者模式和发布订阅模式的区别:参考 https://juejin.im/post/5a14e9edf265da4312808d86

简单说就是,观察者模式中,观察者Observer和被观察者Observable是紧耦合的;而发布订阅模式中,发布者Publisher和订阅者Subscriber是去耦合的,通过第三方Topic或Channel关联。

观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使它们能够进行相应的反应处理。

JDK自带对观察者模式的实现:提供一个被观察者类Observable和观察者接口Observer,被观察者维护了观察者列表在状态改变时会遍历通知所有观察者(因此被观察者和观察者紧耦合)

Observable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
public class Observable {
private boolean changed = false;
private Vector<Observer> obs;

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

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

public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}

public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}

public void notifyObservers() {
notifyObservers(null);
}

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

public synchronized void deleteObservers() {
obs.removeAllElements();
}

protected synchronized void setChanged() {
changed = true;
}

protected synchronized void clearChanged() {
changed = false;
}

public synchronized boolean hasChanged() {
return changed;
}

public synchronized int countObservers() {
return obs.size();
}

Observer:

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
}

我们来举例使用JDK自带的观察者模式:

首先继承Observabe类实现被观察者逻辑:ConcreteObservable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 被观察者,自定义状态,状态变化时通知观察者
*/
public class ConcreteObservable extends Observable {
private String data = "";

public void changeData(String data) {
if (this.data.equalsIgnoreCase ( data )) {
return;
}
this.data = data;
setChanged ();
notifyObservers (data);
}
}

然后实现观察者接口Observer,这儿提供一个实现ConcreteObserver,实际上可以有多个观察者

1
2
3
4
5
6
public class ConcreteObserver implements Observer {
@Override
public void update(Observable o, Object arg) {
System.out.println ( "收到" + o.getClass ().getName () + "的DATA: " + arg +"变化通知" );
}
}

使用类:

1
2
3
4
5
6
7
8
9
public class ObserveUsage {
public static void main(String[] args) {
ConcreteObservable observable = new ConcreteObservable ();
Observer observer = new ConcreteObserver ();
observable.addObserver ( observer ); //向被观察者添加观察者实现一对多通知
observable.changeData ( "FirstMsg" );
observable.changeData ( "SecondMsg" );
}
}

发布订阅模式是观察者模式的升级版,对事件发布方和事件订阅方进行解耦。发布方发布事件,订阅方订阅事件,再通过第三方将发布的事件通知到它的订阅者。

JDK中的事件监听实现了此模式:提供了EventObject类表示具体的事件类型,提供了一个空的监听器接口EventListener,方便扩展使用

我们来举例说明怎么使用事件监听模式:

首先定义一个事件类型基类AppEvent

1
2
3
4
5
6
7
8
9
10
11
12
public class AppEvent extends EventObject {
private final String[] args;

public AppEvent(Object source, String[] args) {
super ( source );
this.args = args;
}

public final String[] getArgs() {
return this.args;
}
}

扩展两个具体的事件类型AppReadyEvent、AppStartingEvent

1
2
3
4
5
6
7
8
9
10
11
12
// 应用启动成功READY事件
public class AppReadyEvent extends AppEvent {
public AppReadyEvent(String[] args) {
super ( "READY_EVENT", args );
}
}
// 应用开始启动事件
public class AppStartingEvent extends AppEvent{
public AppStartingEvent(String[] args) {
super ( "STARTING_EVENT", args );
}
}

定义一个监听器接口AppListener定义事件通知处理协议

1
2
3
4
5
6
public interface AppListener <E extends AppEvent> extends EventListener {
void onAppEvent(E event);
default boolean supportsEventType(Class<? extends AppEvent> eventType) {
return true;
}
}

扩展实现两个具体的监听器PrepareContextAppListener、SendMsgAppListener分别响应两个事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 监听应用开始启动事件,用于准备上下文
public class PrepareContextAppListener implements AppListener<AppStartingEvent> {
@Override
public void onAppEvent(AppStartingEvent event) {
System.out.println ( "PREPARE CONTEXT监听器:" + this.getClass ().getName ()
+"\n收到APP STARTING事件:" + event.getClass ().getName ()
+ "\n收到事件参数:" + Arrays.toString (event.getArgs ()));
}

@Override
public boolean supportsEventType(Class<? extends AppEvent> eventType) {
return AppStartingEvent.class.isAssignableFrom(eventType);
}
}
// 监听应用启动成功事件,用于通知消息
public class SendMsgAppListener implements AppListener<AppReadyEvent> {
@Override
public void onAppEvent(AppReadyEvent event) {
System.out.println ( "SEND MSG监听器:" + this.getClass ().getName () +
"\n收到APP READY事件:" + event.getClass ().getName () +
"\n收到事件参数:" + Arrays.toString (event.getArgs ()));
}

@Override
public boolean supportsEventType(Class<? extends AppEvent> eventType) {
return AppReadyEvent.class.isAssignableFrom(eventType);
}
}

定义一个第三方工具类AppEventMulticaster用于将事件和监听器组合起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 事件广播类:关联事件和监听器
*/
public class AppEventMulticaster {
private Set<AppListener<?>> listeners = new HashSet ();

public void addAppListener(AppListener<?> listener) {
this.listeners.add ( listener );
}

/**
* 根据事件类型自动选择相应的监听器
* @param event
*/
public void multicasterEvent(AppEvent event) {
Iterator var = this.getApplicationListeners(event).iterator();
while(var.hasNext()) {
AppListener<AppEvent> listener = (AppListener)var.next();
listener.onAppEvent ( event );
}
}

/**
* 从所有监听器中选择出监听特定事件的监听器
* @param event
* @return
*/
protected Collection<AppListener<?>> getApplicationListeners(AppEvent event) {
List<AppListener<?>> allListeners = new ArrayList();
Iterator var = listeners.iterator();

while(var.hasNext()) {
AppListener<?> listener = (AppListener)var.next();
if (this.supportsEvent(listener, event.getClass ())) {
allListeners.add(listener);
}
}
return allListeners;
}

/**
* @param listener
* @param eventType
* @return
*/
protected boolean supportsEvent(AppListener<?> listener, Class<? extends AppEvent> eventType) {
return listener.supportsEventType ( eventType );
}

}

最后,我们来使用监听器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 事件监听器模式 (发布订阅模式)
*/
public class EventUsage {
public static void main(String[] args) {
AppEventMulticaster appEventMulticaster = new AppEventMulticaster ();

SendMsgAppListener sendMsgAppListener = new SendMsgAppListener ();
appEventMulticaster.addAppListener ( sendMsgAppListener );

PrepareContextAppListener prepareContextAppListener = new PrepareContextAppListener ();
appEventMulticaster.addAppListener ( prepareContextAppListener );

appEventMulticaster.multicasterEvent ( new AppStartingEvent ( new String[] {"StaringParam1", "StaringParam2"} ));
appEventMulticaster.multicasterEvent ( new AppReadyEvent ( new String[] {"ReadyParam1", "ReadyParam2"} ) );
}
}

输出如下:

1
2
3
4
5
6
PREPARE CONTEXT监听器:com.example.demo.event.PrepareContextAppListener
收到APP STARTING事件:com.example.demo.event.AppStartingEvent
收到事件参数:[StaringParam1, StaringParam2]
SEND MSG监听器:com.example.demo.event.SendMsgAppListener
收到APP READY事件:com.example.demo.event.AppReadyEvent
收到事件参数:[ReadyParam1, ReadyParam2]

可见广播发布具体的事件,相应的监听器会收到通知进行自己的逻辑处理

-------------本文结束感谢您的阅读-------------
Good for you!