一、 观察者(Observer)模式
观察者模式又叫做发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。
观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
一个软件系统常常要求在某一个对象的状态发生变化的时候,某些其它的对象做出相应的改变。做到这一点的设计方案有很多,但是为了使系统能够易于复 用,应该选择低耦合度的设计方案。减少对象之间的耦合有利于系统的复用,但是同时设计师需要使这些低耦合度的对象之间能够维持行动的协调一致,保证高度的 协作(Collaboration)。观察者模式是满足这一要求的各种设计方案中最重要的一种。
二、 观察者模式的结构
观察者模式的类图如下:
![](https://images.cnblogs.com/cnblogs_com/zhenyulu/PicX00105.gif)
可以看出,在这个观察者模式的实现里有下面这些角色:
- 抽象主题(Subject)角色:主题角色把所有对观察考对象的引用保存在一个聚集里,每个主题都可以有任何数量的观察者。抽象主题提供一个接口,可以增加和删除观察者对象,主题角色又叫做抽象被观察者(Observable)角色,一般用一个抽象类或者一个接口实现。
- 抽象观察者(Observer)角色:为所有的具体观察者定义一个接口,在得到主题的通知时更新自己。这个接口叫做更新接口。抽象观察者角色一般用一个抽象类或者一个接口实现。在这个示意性的实现中,更新接口只包含一个方法(即Update()方法),这个方法叫做更新方法。
- 具体主题(ConcreteSubject)角色:将有关状态存入具体现察者对象;在具体主题的内部状态改变时,给所有登记过的观察者发出通知。具体主题角色又叫做具体被观察者角色(Concrete Observable)。具体主题角色通常用一个具体子类实现。
- 具体观察者(ConcreteObserver)角色:存储与主题的状态自恰的状态。具体现察者角色实现抽象观察者角色所要求的更新接口,以便使本身的状态与主题的状态相协调。如果需要,具体现察者角色可以保存一个指向具体主题对象的引用。具体观察者角色通常用一个具体子类实现。
从具体主题角色指向抽象观察者角色的合成关系,代表具体主题对象可以有任意多个对抽象观察者对象的引用。之所以使用抽象观察者而不是具体观察者,意 味着主题对象不需要知道引用了哪些ConcreteObserver类型,而只知道抽象Observer类型。这就使得具体主题对象可以动态地维护一系列 的对观察者对象的引用,并在需要的时候调用每一个观察者共有的Update()方法。这种做法叫做"针对抽象编程"。
三、 观察者模式的示意性源代码
// Observer pattern -- Structural example
using System;
using System.Collections;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// "Subject"
abstract class Subject
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Fields
private ArrayList observers = new ArrayList();
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Methods
public void Attach( Observer observer )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
observers.Add( observer );
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public void Detach( Observer observer )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
observers.Remove( observer );
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public void Notify()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
foreach( Observer o in observers )
o.Update();
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// "ConcreteSubject"
class ConcreteSubject : Subject
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Fields
private string subjectState;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Properties
public string SubjectState
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return subjectState; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ subjectState = value; }
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// "Observer"
abstract class Observer
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Methods
abstract public void Update();
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// "ConcreteObserver"
class ConcreteObserver : Observer
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Fields
private string name;
private string observerState;
private ConcreteSubject subject;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Constructors
public ConcreteObserver( ConcreteSubject subject,
string name )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.subject = subject;
this.name = name;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Methods
override public void Update()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
observerState = subject.SubjectState;
Console.WriteLine( "Observer {0}'s new state is {1}",
name, observerState );
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Properties
public ConcreteSubject Subject
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return subject; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ subject = value; }
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**//// <summary>
/// Client test
/// </summary>
public class Client
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public static void Main( string[] args )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// Configure Observer structure
ConcreteSubject s = new ConcreteSubject();
s.Attach( new ConcreteObserver( s, "1" ) );
s.Attach( new ConcreteObserver( s, "2" ) );
s.Attach( new ConcreteObserver( s, "3" ) );
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Change subject and notify observers
s.SubjectState = "ABC";
s.Notify();
}
}
四、 C#中的Delegate与Event
实际上在C#中实现Observer模式没有这么辛苦,.NET中提供了Delegate与Event机制,我们可以利用这种机制简化Observer模式。关于Delegate与Event的使用方法请参考相关文档。改进后的Observer模式实现如下:
// Observer pattern -- Structural example
using System;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
//Delegate
delegate void UpdateDelegate();
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
//Subject
class Subject
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public event UpdateDelegate UpdateHandler;
// Methods
public void Attach( UpdateDelegate ud )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
UpdateHandler += ud;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public void Detach( UpdateDelegate ud )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
UpdateHandler -= ud;
}
public void Notify()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if(UpdateHandler != null) UpdateHandler();
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
//ConcreteSubject
class ConcreteSubject : Subject
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Fields
private string subjectState;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Properties
public string SubjectState
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return subjectState; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ subjectState = value; }
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// "ConcreteObserver"
class ConcreteObserver
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Fields
private string name;
private string observerState;
private ConcreteSubject subject;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Constructors
public ConcreteObserver( ConcreteSubject subject,
string name )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.subject = subject;
this.name = name;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Methods
public void Update()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
observerState = subject.SubjectState;
Console.WriteLine( "Observer {0}'s new state is {1}",
name, observerState );
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Properties
public ConcreteSubject Subject
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return subject; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ subject = value; }
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// "ConcreteObserver"
class AnotherObserver
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Methods
public void Show()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.WriteLine("AnotherObserver got an Notification!");
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
public class Client
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public static void Main(string[] args)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
ConcreteSubject s = new ConcreteSubject();
ConcreteObserver o1 = new ConcreteObserver(s, "1");
ConcreteObserver o2 = new ConcreteObserver(s, "2");
AnotherObserver o3 = new AnotherObserver();
s.Attach(new UpdateDelegate(o1.Update));
s.Attach(new UpdateDelegate(o2.Update));
s.Attach(new UpdateDelegate(o3.Show));
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
s.SubjectState = "ABC";
s.Notify();
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
Console.WriteLine("--------------------------");
s.Detach(new UpdateDelegate(o1.Update));
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
s.SubjectState = "DEF";
s.Notify();
}
} 其中,关键的代码如下:
delegate void UpdateDelegate(); 定义一个Delegate,用来规范函数结构。不管是ConcreteObserver类的Update方法还是AnotherObserver类 的Show方法都符合该Delegate。这不象用Observer接口来规范必须使用Update方法那么严格。只要符合Delegate所指定的方法 结构的方法都可以在后面被事件所处理。
public event UpdateDelegate UpdateHandler; 定义一个事件,一旦触发,可以调用一组符合UpdateDelegate规范的方法。
public void Attach( UpdateDelegate ud )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
UpdateHandler += ud;
} 订阅事件。只要是一个满足UpdateDelegate的方法,就可以进行订阅操作(如下所示)。
s.Attach(new UpdateDelegate(o1.Update));
s.Attach(new UpdateDelegate(o2.Update));
s.Attach(new UpdateDelegate(o3.Show)); 在Notify方法中:
public void Notify()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
if(UpdateHandler != null) UpdateHandler();
} 只要UpdateHandler != null(表示有订阅者),就可以触发事件(UpdateHandler()),所有的订阅者便会接到通知。
五、 一个实际应用观察者模式的例子
该例子演示了注册的投资者在股票市场发生变化时,可以自动得到通知。该例子仍然使用的是传统的Observer处理手段,至于如何转换成Delegate与Event留给读者自己考虑。
// Observer pattern -- Real World example
using System;
using System.Collections;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// "Subject"
abstract class Stock
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Fields
protected string symbol;
protected double price;
private ArrayList investors = new ArrayList();
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Constructor
public Stock( string symbol, double price )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.symbol = symbol;
this.price = price;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Methods
public void Attach( Investor investor )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
investors.Add( investor );
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public void Detach( Investor investor )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
investors.Remove( investor );
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public void Notify()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
foreach( Investor i in investors )
i.Update( this );
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Properties
public double Price
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return price; }
set
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
price = value;
Notify();
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
public string Symbol
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return symbol; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ symbol = value; }
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// "ConcreteSubject"
class IBM : Stock
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Constructor
public IBM( string symbol, double price )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
: base( symbol, price )
{}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// "Observer"
interface IInvestor
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Methods
void Update( Stock stock );
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// "ConcreteObserver"
class Investor : IInvestor
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
// Fields
private string name;
private string observerState;
private Stock stock;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Constructors
public Investor( string name )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.name = name;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Methods
public void Update( Stock stock )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.WriteLine( "Notified investor {0} of {1}'s change to {2:C}",
name, stock.Symbol, stock.Price );
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Properties
public Stock Stock
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return stock; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ stock = value; }
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**//// <summary>
/// ObserverApp test
/// </summary>
public class ObserverApp
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
public static void Main( string[] args )
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// Create investors
Investor s = new Investor( "Sorros" );
Investor b = new Investor( "Berkshire" );
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Create IBM stock and attach investors
IBM ibm = new IBM( "IBM", 120.00 );
ibm.Attach( s );
ibm.Attach( b );
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Change price, which notifies investors
ibm.Price = 120.10;
ibm.Price = 121.00;
ibm.Price = 120.50;
ibm.Price = 120.75;
}
}
六、 观察者模式的优缺点
Observer模式的优点是实现了表示层和数据逻辑层的分离,并定义了稳定的更新消息传递机制,类别清晰,并抽象了更新接口,使得可以有各种各样不同的表示层(观察者)。
但是其缺点是每个外观对象必须继承这个抽像出来的接口类,这样就造成了一些不方便,比如有一个别人写的外观对象,并没有继承该抽象类,或者接口不 对,我们又希望不修改该类直接使用它。虽然可以再应用Adapter模式来一定程度上解决这个问题,但是会造成更加复杂烦琐的设计,增加出错几率。
观察者模式的效果有以下几个优点:
(1)观察者模式在被观察者和观察者之间建立一个抽象的耦合。被观察者角色所知道的只是一个具体现察者聚集,每一个具体现察者都符合一个抽象观察者 的接口。被观察者并不认识任何一个具体观察者,它只知道它们都有一个共同的接口。由于被观察者和观察者没有紧密地耦合在一起,因此它们可以属于不同的抽象 化层次。
(2)观察者模式支持广播通信。被观察者会向所有的登记过的观察者发出通知。
观察者模式有下面的一些缺点:
(1)如果一个被观察者对象有很多直接和间接的观察者的话,将所有的观察者都通知到会花费很多时间。
(2)如果在被观察者之间有循环依赖的话,被观察者会触发它们之间进行循环调用,导致系统崩溃。在使用观察考模式时要特别注意这一点。
(3)如果对观察者的通知是通过另外的线程进行异步投递的话,系统必须保证投递是以自恰的方式进行的。
(4)虽然观察者模式可以随时使观察者知道所观察的对象发生了变化,但是观察者模式没有相应的机制使观察者知道所观察的对象是怎么发生变化的。