博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计模式-Observer Pattern
阅读量:6875 次
发布时间:2019-06-26

本文共 8360 字,大约阅读时间需要 27 分钟。

  hot3.png

一、 观察者(Observer)模式

观察者模式又叫做发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。

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

一 个软件系统常常要求在某一个对象的状态发生变化的时候,某些其它的对象做出相应的改变。做到这一点的设计方案有很多,但是为了使系统能够易于复用,应该选 择低耦合度的设计方案。减少对象之间的耦合有利于系统的复用,但是同时设计师需要使这些低耦合度的对象之间能够维持行动的协调一致,保证高度的协作 (Collaboration)。观察者模式是满足这一要求的各种设计方案中最重要的一种。

二、 观察者模式的结构

观察者模式的类图如下:

 PicX00105.gif

可以看出,在这个观察者模式的实现里有下面这些角色:

  • 抽象主题(Subject)角色:主题角色把所有对观察考对象的引用保存在一个聚集里,每个主题都可以有任何数量的观察者。抽象主题提供一个接口,可以增加和删除观察者对象,主题角色又叫做抽象被观察者(Observable)角色,一般用一个抽象类或者一个接口实现。
  • 抽象观察者(Observer)角色:为所有的具体观察者定义一个接口,在得到主题的通知时更新自己。这个接口叫做更新接口。抽象观察者角色一般用一个抽象类或者一个接口实现。在这个示意性的实现中,更新接口只包含一个方法(即Update()方法),这个方法叫做更新方法。
  • 具体主题(ConcreteSubject)角色:将有关状态存入具体现察者对象;在具体主题的内部状态改变时,给所有登记过的观察者发出通知。具体主题角色又叫做具体被观察者角色(Concrete Observable)。具体主题角色通常用一个具体子类实现。
  • 具体观察者(ConcreteObserver)角色:存储与主题的状态自恰的状态。具体现察者角色实现抽象观察者角色所要求的更新接口,以便使本身的状态与主题的状态相协调。如果需要,具体现察者角色可以保存一个指向具体主题对象的引用。具体观察者角色通常用一个具体子类实现。

从 具体主题角色指向抽象观察者角色的合成关系,代表具体主题对象可以有任意多个对抽象观察者对象的引用。之所以使用抽象观察者而不是具体观察者,意味着主题 对象不需要知道引用了哪些ConcreteObserver类型,而只知道抽象Observer类型。这就使得具体主题对象可以动态地维护一系列的对观察 者对象的引用,并在需要的时候调用每一个观察者共有的Update()方法。这种做法叫做"针对抽象编程"。

三、 观察者模式的示意性源代码

None.gif
//
 Observer pattern -- Structural example  
None.gif
using
 System;
None.gif
using
 System.Collections;
None.gif
None.gif
//
 "Subject"
None.gif
abstract
 
class
 Subject
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Fields
InBlock.gif
  
private
 ArrayList observers 
=
 
new
 ArrayList();
InBlock.gif
InBlock.gif  
//
 Methods
InBlock.gif
  
public
 
void
 Attach( Observer observer )
ExpandedSubBlockStart.gif  
{
InBlock.gif    observers.Add( observer );
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
public
 
void
 Detach( Observer observer )
ExpandedSubBlockStart.gif  
{
InBlock.gif    observers.Remove( observer );
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
public
 
void
 Notify()
ExpandedSubBlockStart.gif  
{
InBlock.gif    
foreach
( Observer o 
in
 observers )
InBlock.gif      o.Update();
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}
None.gif
None.gif
//
 "ConcreteSubject"
None.gif
class
 ConcreteSubject : Subject
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Fields
InBlock.gif
  
private
 
string
 subjectState;
InBlock.gif
InBlock.gif  
//
 Properties
InBlock.gif
  
public
 
string
 SubjectState
ExpandedSubBlockStart.gif  
{
ExpandedSubBlockStart.gif    
get
return
 subjectState; }
ExpandedSubBlockStart.gif    
set
{ subjectState 
=
 value; }
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}
None.gif
None.gif
//
 "Observer"
None.gif
abstract
 
class
 Observer
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Methods
InBlock.gif
  
abstract
 
public
 
void
 Update();
ExpandedBlockEnd.gif}
None.gif
None.gif
//
 "ConcreteObserver"
None.gif
class
 ConcreteObserver : Observer
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Fields
InBlock.gif
  
private
 
string
 name;
InBlock.gif  
private
 
string
 observerState;
InBlock.gif  
private
 ConcreteSubject subject;
InBlock.gif
InBlock.gif  
//
 Constructors
InBlock.gif
  
public
 ConcreteObserver( ConcreteSubject subject,  
InBlock.gif    
string
 name )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
this
.subject 
=
 subject;
InBlock.gif    
this
.name 
=
 name;
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
//
 Methods
InBlock.gif
  
override
 
public
 
void
 Update()
ExpandedSubBlockStart.gif  
{
InBlock.gif    observerState 
=
 subject.SubjectState;
InBlock.gif    Console.WriteLine( 
"
Observer {0}'s new state is {1}
"
,
InBlock.gif      name, observerState );
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
//
 Properties
InBlock.gif
  
public
 ConcreteSubject Subject
ExpandedSubBlockStart.gif  
{
ExpandedSubBlockStart.gif    
get
 
return
 subject; }
ExpandedSubBlockStart.gif    
set
 
{ subject 
=
 value; }
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}
None.gif
ExpandedBlockStart.gif
///
 
<summary>
InBlock.gif
///
 Client test
ExpandedBlockEnd.gif
///
 
</summary>
None.gif
public
 
class
 Client
ExpandedBlockStart.gif
{
InBlock.gif  
public
 
static
 
void
 Main( 
string
[] args )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
//
 Configure Observer structure
InBlock.gif
    ConcreteSubject s 
=
 
new
 ConcreteSubject();
InBlock.gif    s.Attach( 
new
 ConcreteObserver( s, 
"
1
"
 ) );
InBlock.gif    s.Attach( 
new
 ConcreteObserver( s, 
"
2
"
 ) );
InBlock.gif    s.Attach( 
new
 ConcreteObserver( s, 
"
3
"
 ) );
InBlock.gif
InBlock.gif    
//
 Change subject and notify observers
InBlock.gif
    s.SubjectState 
=
 
"
ABC
"
;
InBlock.gif    s.Notify();
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}

四、 C#中的Delegate与Event

实际上在C#中实现Observer模式没有这么辛苦,.NET中提供了Delegate与Event机制,我们可以利用这种机制简化Observer模式。关于Delegate与Event的使用方法请参考相关文档。改进后的Observer模式实现如下:

None.gif
//
 Observer pattern -- Structural example  
None.gif
using
 System;
None.gif
None.gif
//
Delegate
None.gif
delegate
 
void
 UpdateDelegate(); 
None.gif
None.gif
//
Subject
None.gif
class
 Subject
ExpandedBlockStart.gif
{
InBlock.gif  
public
 
event
 UpdateDelegate UpdateHandler;
InBlock.gif  
InBlock.gif  
//
 Methods
InBlock.gif
  
public
 
void
 Attach( UpdateDelegate ud )
ExpandedSubBlockStart.gif  
{
InBlock.gif    UpdateHandler 
+=
 ud;
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
public
 
void
 Detach( UpdateDelegate ud )
ExpandedSubBlockStart.gif  
{
InBlock.gif    UpdateHandler 
-=
 ud;
ExpandedSubBlockEnd.gif  }
InBlock.gif  
InBlock.gif  
public
 
void
 Notify()
ExpandedSubBlockStart.gif  
{
InBlock.gif    
if
(UpdateHandler 
!=
 
null
) UpdateHandler();
ExpandedSubBlockEnd.gif  }
InBlock.gif
ExpandedBlockEnd.gif}
None.gif
None.gif
//
ConcreteSubject
None.gif
class
 ConcreteSubject : Subject
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Fields
InBlock.gif
  
private
 
string
 subjectState;
InBlock.gif
InBlock.gif  
//
 Properties
InBlock.gif
  
public
 
string
 SubjectState
ExpandedSubBlockStart.gif  
{
ExpandedSubBlockStart.gif    
get
return
 subjectState; }
ExpandedSubBlockStart.gif    
set
{ subjectState 
=
 value; }
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}
None.gif
None.gif
//
 "ConcreteObserver"
None.gif
class
 ConcreteObserver
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Fields
InBlock.gif
  
private
 
string
 name;
InBlock.gif  
private
 
string
 observerState;
InBlock.gif  
private
 ConcreteSubject subject;
InBlock.gif
InBlock.gif  
//
 Constructors
InBlock.gif
  
public
 ConcreteObserver( ConcreteSubject subject,  
InBlock.gif    
string
 name )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
this
.subject 
=
 subject;
InBlock.gif    
this
.name 
=
 name;
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
//
 Methods
InBlock.gif
  
public
 
void
 Update()
ExpandedSubBlockStart.gif  
{
InBlock.gif    observerState 
=
 subject.SubjectState;
InBlock.gif    Console.WriteLine( 
"
Observer {0}'s new state is {1}
"
,
InBlock.gif      name, observerState );
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
//
 Properties
InBlock.gif
  
public
 ConcreteSubject Subject
ExpandedSubBlockStart.gif  
{
ExpandedSubBlockStart.gif    
get
 
return
 subject; }
ExpandedSubBlockStart.gif    
set
 
{ subject 
=
 value; }
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}
None.gif
None.gif
//
 "ConcreteObserver"
None.gif
class
 AnotherObserver
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Methods
InBlock.gif
  
public
 
void
 Show()
ExpandedSubBlockStart.gif  
{
InBlock.gif    Console.WriteLine(
"
AnotherObserver got an Notification!
"
);
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}
None.gif
None.gif
public
 
class
 Client
ExpandedBlockStart.gif
InBlock.gif  
public
 
static
 
void
 Main(
string
[] args)
ExpandedSubBlockStart.gif  
InBlock.gif    ConcreteSubject s 
=
 
new
 ConcreteSubject();
InBlock.gif    ConcreteObserver o1 
=
 
new
 ConcreteObserver(s, 
"
1
"
);
InBlock.gif    ConcreteObserver o2 
=
 
new
 ConcreteObserver(s, 
"
2
"
);
InBlock.gif    AnotherObserver o3 
=
 
new
 AnotherObserver();
InBlock.gif    
InBlock.gif    s.Attach(
new
 UpdateDelegate(o1.Update));
InBlock.gif    s.Attach(
new
 UpdateDelegate(o2.Update));
InBlock.gif    s.Attach(
new
 UpdateDelegate(o3.Show));
InBlock.gif
InBlock.gif    s.SubjectState 
=
 
"
ABC
"
;
InBlock.gif    s.Notify();
InBlock.gif
InBlock.gif    Console.WriteLine(
"
--------------------------
"
);
InBlock.gif    s.Detach(
new
 UpdateDelegate(o1.Update));
InBlock.gif
InBlock.gif    s.SubjectState 
=
 
"
DEF
"
;
InBlock.gif    s.Notify();
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}

其中,关键的代码如下:

None.gif
delegate
 
void
 UpdateDelegate(); 

定 义一个Delegate,用来规范函数结构。不管是ConcreteObserver类的Update方法还是AnotherObserver类的 Show方法都符合该Delegate。这不象用Observer接口来规范必须使用Update方法那么严格。只要符合Delegate所指定的方法结 构的方法都可以在后面被事件所处理。

None.gif
public
 
event
 UpdateDelegate UpdateHandler;

定义一个事件,一旦触发,可以调用一组符合UpdateDelegate规范的方法。

None.gif
  
public
 
void
 Attach( UpdateDelegate ud )
ExpandedBlockStart.gif  
{
InBlock.gif    UpdateHandler 
+=
 ud;
ExpandedBlockEnd.gif  }

订阅事件。只要是一个满足UpdateDelegate的方法,就可以进行订阅操作(如下所示)。

None.gif
    s.Attach(
new
 UpdateDelegate(o1.Update));
None.gif    s.Attach(
new
 UpdateDelegate(o2.Update));
None.gif    s.Attach(
new
 UpdateDelegate(o3.Show));

在Notify方法中:

None.gif
  
public
 
void
 Notify()
ExpandedBlockStart.gif  
{
InBlock.gif    
if
(UpdateHandler 
!=
 
null
) UpdateHandler();
ExpandedBlockEnd.gif  }

只要UpdateHandler != null(表示有订阅者),就可以触发事件(UpdateHandler()),所有的订阅者便会接到通知。

五、 一个实际应用观察者模式的例子

该例子演示了注册的投资者在股票市场发生变化时,可以自动得到通知。该例子仍然使用的是传统的Observer处理手段,至于如何转换成Delegate与Event留给读者自己考虑。

None.gif
//
 Observer pattern -- Real World example  
None.gif
using
 System;
None.gif
using
 System.Collections;
None.gif
None.gif
//
 "Subject"
None.gif
abstract
 
class
 Stock
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Fields
InBlock.gif
  
protected
 
string
 symbol;
InBlock.gif  
protected
 
double
 price;
InBlock.gif  
private
 ArrayList investors 
=
 
new
 ArrayList();
InBlock.gif
InBlock.gif  
//
 Constructor
InBlock.gif
  
public
 Stock( 
string
 symbol, 
double
 price )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
this
.symbol 
=
 symbol;
InBlock.gif    
this
.price 
=
 price;
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
//
 Methods
InBlock.gif
  
public
 
void
 Attach( Investor investor )
ExpandedSubBlockStart.gif  
{
InBlock.gif    investors.Add( investor );
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
public
 
void
 Detach( Investor investor )
ExpandedSubBlockStart.gif  
{
InBlock.gif    investors.Remove( investor );
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
public
 
void
 Notify()
ExpandedSubBlockStart.gif  
{
InBlock.gif    
foreach
( Investor i 
in
 investors )
InBlock.gif      i.Update( 
this
 );
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
//
 Properties
InBlock.gif
  
public
 
double
 Price
ExpandedSubBlockStart.gif  
{
ExpandedSubBlockStart.gif    
get
return
 price; }
InBlock.gif    
set
ExpandedSubBlockStart.gif    
{
InBlock.gif      price 
=
 value;
InBlock.gif      Notify(); 
ExpandedSubBlockEnd.gif    }
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
public
 
string
 Symbol
ExpandedSubBlockStart.gif  
{
ExpandedSubBlockStart.gif    
get
return
 symbol; }
ExpandedSubBlockStart.gif    
set
{ symbol 
=
 value; }
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}
None.gif
None.gif
//
 "ConcreteSubject"
None.gif
class
 IBM : Stock
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Constructor
InBlock.gif
  
public
 IBM( 
string
 symbol, 
double
 price )
ExpandedSubBlockStart.gif    : 
base
( symbol, price ) 
{}
ExpandedBlockEnd.gif}
None.gif
None.gif
//
 "Observer"
None.gif
interface
 IInvestor
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Methods
InBlock.gif
  
void
 Update( Stock stock );
ExpandedBlockEnd.gif}
None.gif
None.gif
//
 "ConcreteObserver"
None.gif
class
 Investor : IInvestor
ExpandedBlockStart.gif
{
InBlock.gif  
//
 Fields
InBlock.gif
  
private
 
string
 name;
InBlock.gif  
private
 
string
 observerState;
InBlock.gif  
private
 Stock stock;
InBlock.gif
InBlock.gif  
//
 Constructors
InBlock.gif
  
public
 Investor( 
string
 name )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
this
.name 
=
 name;
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
//
 Methods
InBlock.gif
  
public
 
void
 Update( Stock stock )
ExpandedSubBlockStart.gif  
{
InBlock.gif    Console.WriteLine( 
"
Notified investor {0} of {1}'s change to {2:C}
"
InBlock.gif      name, stock.Symbol, stock.Price );
ExpandedSubBlockEnd.gif  }
InBlock.gif
InBlock.gif  
//
 Properties
InBlock.gif
  
public
 Stock Stock
ExpandedSubBlockStart.gif  
{
ExpandedSubBlockStart.gif    
get
return
 stock; }
ExpandedSubBlockStart.gif    
set
{ stock 
=
 value; }
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}
None.gif
ExpandedBlockStart.gif
///
 
<summary>
InBlock.gif
///
 ObserverApp test
ExpandedBlockEnd.gif
///
 
</summary>
None.gif
public
 
class
 ObserverApp
ExpandedBlockStart.gif
{
InBlock.gif  
public
 
static
 
void
 Main( 
string
[] args )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
//
 Create investors
InBlock.gif
    Investor s 
=
 
new
 Investor( 
"
Sorros
"
 );
InBlock.gif    Investor b 
=
 
new
 Investor( 
"
Berkshire
"
 );
InBlock.gif
InBlock.gif    
//
 Create IBM stock and attach investors
InBlock.gif
    IBM ibm 
=
 
new
 IBM( 
"
IBM
"
120.00
 );
InBlock.gif    ibm.Attach( s );
InBlock.gif    ibm.Attach( b );
InBlock.gif
InBlock.gif    
//
 Change price, which notifies investors
InBlock.gif
    ibm.Price 
=
 
120.10
;
InBlock.gif    ibm.Price 
=
 
121.00
;
InBlock.gif    ibm.Price 
=
 
120.50
;
InBlock.gif    ibm.Price 
=
 
120.75
;
ExpandedSubBlockEnd.gif  }
ExpandedBlockEnd.gif}

六、 观察者模式的优缺点

Observer模式的优点是实现了表示层和数据逻辑层的分离,并定义了稳定的更新消息传递机制,类别清晰,并抽象了更新接口,使得可以有各种各样不同的表示层(观察者)。

但 是其缺点是每个外观对象必须继承这个抽像出来的接口类,这样就造成了一些不方便,比如有一个别人写的外观对象,并没有继承该抽象类,或者接口不对,我们又 希望不修改该类直接使用它。虽然可以再应用Adapter模式来一定程度上解决这个问题,但是会造成更加复杂烦琐的设计,增加出错几率。

观察者模式的效果有以下几个优点:

(1) 观察者模式在被观察者和观察者之间建立一个抽象的耦合。被观察者角色所知道的只是一个具体现察者聚集,每一个具体现察者都符合一个抽象观察者的接口。被观 察者并不认识任何一个具体观察者,它只知道它们都有一个共同的接口。由于被观察者和观察者没有紧密地耦合在一起,因此它们可以属于不同的抽象化层次。

(2)观察者模式支持广播通信。被观察者会向所有的登记过的观察者发出通知。

观察者模式有下面的一些缺点:

(1)如果一个被观察者对象有很多直接和间接的观察者的话,将所有的观察者都通知到会花费很多时间。

(2)如果在被观察者之间有循环依赖的话,被观察者会触发它们之间进行循环调用,导致系统崩溃。在使用观察考模式时要特别注意这一点。

(3)如果对观察者的通知是通过另外的线程进行异步投递的话,系统必须保证投递是以自恰的方式进行的。

(4)虽然观察者模式可以随时使观察者知道所观察的对象发生了变化,但是观察者模式没有相应的机制使观察者知道所观察的对象是怎么发生变化的。

参考文献:
阎宏,《Java与模式》,电子工业出版社
[美]James W. Cooper,《C#设计模式》,电子工业出版社
[美]Alan Shalloway  James R. Trott,《Design Patterns Explained》,中国电力出版社
[美]Robert C. Martin,《敏捷软件开发-原则、模式与实践》,清华大学出版社
[美]Don Box, Chris Sells,《.NET本质论 第1卷:公共语言运行库》,中国电力出版社

转载于:https://my.oschina.net/qihh/blog/57810

你可能感兴趣的文章
Glide 知识梳理(4) 自定义animate
查看>>
Android 注解系列之Annotation(二)
查看>>
JavaEE进阶知识学习-----SpringCloud(五)Eureka和Zookeeper区别
查看>>
Function构造函数、 函数声明 、 函数表达式 的区别
查看>>
类似if一样的自定义代码块
查看>>
[译]如何在 iOS 上实现类似 Airbnb 中的可展开式菜单
查看>>
极光推送集成Module中遇到的坑
查看>>
读书笔记 Effective Objective C 2 0 (未完待续)
查看>>
利用transform实现表头固定
查看>>
使用SSH RSA key免密码登录Linux服务器
查看>>
如何绑定页面生命周期(二)-基于Android Architecture Components的Lifecycle实现
查看>>
互联网安全内容安全及防护
查看>>
Nginx location配置解析
查看>>
element 学习借鉴 p1
查看>>
给富文本内容中的图片添加一个与App端交互事件
查看>>
JavaScript 编年小史
查看>>
Python大佬分析了15万歌词,告诉你民谣歌手们到底在唱什么
查看>>
教你用一条SQL搞定跨数据库查询难题
查看>>
09 用MaterialRefreshLayout实现下拉刷新&上拉加载更多(与服务器交互)
查看>>
零基础带你吃掉JNI全家桶(三)
查看>>