您的位置:首页 > 其它

[Head First设计模式]山西面馆中的设计模式——观察者模式

2013-12-14 12:20 751 查看

系列文章

[Head First设计模式]山西面馆中的设计模式——装饰者模式

引言

不知不自觉又将设计模式融入生活了,吃个饭也不得安生,也发现生活中的很多场景,都可以用设计模式来模拟。原来设计模式就在我身边。


为什么观察者模式会出现呢?

为了建立一种对象与对象之间的依赖关系,一个对象发生改变时将自动通知其他对象,其他对象将相应做出反应。在此,发生改变的对象称为观察目标,而被通知的对象称为观察者,一个观察目标可以对应多个观察者,而且这些观察者之间没有相互联系,可以根据需要增加和删除观察者,使得系统更易于扩展,这就是为什么需要观察者模式。


观察者模式定义

观察者模式(Observer Pattern):定义了对象之间的一种一对多依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象皆得到通知并被自动更新。观察者模式又被称为发布-订阅(Publish/Subscribe)模式,模型-视图(Model/View)模式,源-监听器(Source/Listener)模式,或从属者(Dependents)模式。观察者模式是一种对象行为型的模式。

观察者模式UML



当两个对象是松耦合的,它们之间能够交互,但是相互了解的很少。

观察者模式提供了主题和观察者之间的松耦合设计。因为主题只知道观察者实现了某个接口(即Observer接口)。主题不需要知道具体观察者是谁,做了些什么或其它任何细节。要增加新的观察者或删除观察者,主题不会受到任何影响,不必修改主题代码。

可以独立地复用主题和观察者,他们之间互不影响,即是松耦合。


设计原则:在交互的对象之间争取松耦合设计

由于松耦合设计使得对象间的依赖最小化,所以,我们能够创建柔性的oo系统,应对变化的情况,因为对象间的依赖降到了最低。


实例分析

书中的气象站例子:



代码实现:

public interface  Subject
{
void RegisterObserver(Observer o);//这两个方法都需要一个观察者作为参数,该观察者是用来注册或被删除的。
void RemoveObserver(Observer o);
void NotifyObservers();//当主题改变状态时,这个方法会被调用,以通知所有的观察者
}


public interface Observer
{
/// <summary>
/// 当气象观测值改变时,主题会把这些状态值作为方法的参数传给观察者
/// </summary>
/// <param name="temp"></param>
/// <param name="humidity"></param>
/// <param name="pressure"></param>
void Update(float temp,float humidity,float pressure);
}


/// <summary>
/// 该接口之包含一个方法,也就是display方法,当布告板需要显示时,调用次方法。
/// </summary>
public interface DisplayElement
{
void Display();
}


在WeatherData中实现主题接口

/// <summary>
/// WeatherData实现了subject接口
/// </summary>
public class WeatherData : Subject
{
/// <summary>
/// 我们加上一个ArrayList来记录观察者,此ArrayList是在构造器中建立的
/// </summary>
private ArrayList observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData()
{
observers = new ArrayList();
}
public void RegisterObserver(Observer o)
{
//当注册观察者的时候,秩序把他们加在ArrayList后面就行了
observers.Add(o);
}

public void RemoveObserver(Observer o)
{
//同样,当观察者想取消注册,只需要移除
int i = observers.IndexOf(o);
if (i > 0)
{
observers.Remove(i);
}
}
/// <summary>
/// 有趣的地方来了,在这里,我们把状态告诉每一个观察者,
/// 因为观察者都实现了Update方法,所以我们知道如何通知他们
/// </summary>
public void NotifyObservers()
{
for (int i = 0; i < observers.Count; i++)
{
Observer observer = (Observer)observers[i];
observer.Update(temperature, humidity, pressure);
}
}
/// <summary>
/// 当气象站得到更新观测值的时,我们通知观察者。
/// </summary>
public void MeasurementChanged() {
NotifyObservers();
}
public void SetMeasurements(float temperature, float humidity, float pressure)
{
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
}
}


建立布告板

/// <summary>
/// 此布告板实现了Observer接口,所以可以从weatherdata对象中获得改变,
/// 同时也实现了DisplayElement接口,因为我们的API规定所有的布告板必须实现此接口
/// </summary>
public class CurrentConditionsDisplay:Observer,DisplayElement
{
private float temperature;
private float humidity;

private Subject weatherData;
/// <summary>
/// 构造器需要weatherdata对象作为注册用
/// </summary>
/// <param name="weatherData"></param>
public CurrentConditionsDisplay(Subject weatherData)
{
this.weatherData = weatherData;
weatherData.RegisterObserver(this);
}
public void Update(float temp, float humidity, float pressure)
{
//当update被调用的时候,我们把温度和湿度保存起来,然后调用Display();
this.temperature = temp;
this.humidity = humidity;
Display();

}
/// <summary>
/// 只是将最近的湿度和温度显示出来。
/// </summary>
public void Display()
{
Console.WriteLine("Current conditions:"+temperature+" F degrees and"+humidity+"% humidity");
}
}


测试代码

class Program
{
static void Main(string[] args)
{
//首先创建weatherData对象
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
weatherData.SetMeasurements(80, 65, 30.4f);
//通知
weatherData.NotifyObservers();
weatherData.SetMeasurements(82, 70, 29.2f);
weatherData.NotifyObservers();
weatherData.SetMeasurements(78, 90, 29.2f);
weatherData.NotifyObservers();
Console.Read();
}
}


结果:



实例分析二

场景:山西面馆中,我点餐,服务员传话给厨师,厨师应答,厨师做饭。

分析:在这个场景中,我:被观察者,服务员,厨师:观察者。

我:“一份西红柿鸡蛋汤面”

一系列动作

服务员:1.向厨师传话“一份西红柿鸡蛋汤面”

厨师:1.收到,2.开始做。

在.NET中,C#使用委托以及事件,可以很好的实现观察者模式。委托相当于“订阅清单”的角色,当目标中关联了该委托的事件被触发时,则委托将自动按序执行观察者注册于委托中的方法。

代码实现:

基类的实现

/// <summary>
/// 自定义事件参数
/// </summary>
public class EatSomthingEventArgs : EventArgs
{
private string foodName;
public EatSomthingEventArgs(string foodName)
{
this.foodName = foodName;
}
public string FoodName
{
get { return foodName; }
set { foodName = value; }
}


/// <summary>
/// 声明一个委托,用于代理一系列自定义方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void EatSomethingEventHandler(object sender, EatSomthingEventArgs e);


/// <summary>
///  在Observer Pattern(观察者模式)中,此类作为所有Subject(主题)的抽象基类
/// 此抽象类无抽象方法,主要是为了不能实例化该类对象,确保模式完整性.
/// 具体的主题(比如:customer)就继承自该类,也可以说是被观察者的基类。
/// </summary>
public abstract class Subject
{
public event EatSomethingEventHandler EatSomethingHandler;
public string FoodName { set; get; }
/// <summary>
///  封装了触发事件的方法
/// 主要为了规范化及安全性,除观察者基类外,其派生类不直接触发委托事件
/// </summary>
protected void Notify()
{
if (EatSomethingHandler != null)
{
EatSomethingHandler(this, new EatSomthingEventArgs(this.FoodName));
}
}
}


/// <summary>
/// 此类作为所有Observer(观察者)的抽象基类
/// 此类作为观察者基类,用于规划所有观察者(即订阅方)订阅行为
/// 具体实施过程:
///     1.指定观察者所观察的对象(即发布方).(通过构造器传递)
///     2.规划观察者自身需要作出响应方法列表
///     3.注册需要委托执行的方法.(通过构造器实现)
/// </summary>
public abstract class Observer
{
/// <summary>
/// 构造时通过传入具体主题subject,把观察者与模型关联,并完成订阅.
/// </summary>
/// <param name="subject"></param>
public Observer(Subject subject)
{
subject.EatSomethingHandler += new EatSomethingEventHandler(Response);
}
/// <summary>
/// 规划了观察者的一种行为(方法),所有派生于该观察者基类的具体观察者都
/// 通过覆盖该方法来实现作出响应的行为.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public abstract void Response(object sender, EatSomthingEventArgs e);
}


/// <summary>
/// 另一个观察者基类.该观察者类型拥有两个响应行为
/// </summary>
public abstract class Observer2
{/// <summary>
/// 构造时通过传入具体主题subject,把观察者与模型关联,并完成订阅.
/// </summary>
/// <param name="subject"></param>
public Observer2(Subject subject)
{
subject.EatSomethingHandler += new EatSomethingEventHandler(Response);
subject.EatSomethingHandler += new EatSomethingEventHandler(Response2);
}
/// <summary>
/// 规划了观察者的一种行为(方法),所有派生于该观察者基类的具体观察者都
/// 通过覆盖该方法来实现作出响应的行为.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public abstract void Response(object sender, EatSomthingEventArgs e);
public abstract void Response2(object sender, EatSomthingEventArgs e);
}


观察者实现

/// <summary>
/// 厨师类 继承自抽象观察者基类Observer2 两个反应
/// </summary>
public class Cook : Observer2
{
public Cook(Subject subject)
: base(subject)
{ }
public override void Response(object sender, EatSomthingEventArgs e)
{
Console.WriteLine("厨师:收到了,要做一份{0}", e.FoodName);
}

public override void Response2(object sender, EatSomthingEventArgs e)
{
Console.WriteLine("厨师:{0}已经在做了,稍等.....", e.FoodName);
}
}


/// <summary>
/// 具体的观察者 服务员 继承自观察者基类
/// </summary>
public class Waiter : Observer
{
public Waiter(Subject subject)
: base(subject)
{ }
public override void Response(object sender, EatSomthingEventArgs e)
{
Console.WriteLine("美女服务员:康师傅做一份{0}", e.FoodName);
}
}


被观察者

/// <summary>
/// 具体的主题类 即被观察者
/// </summary>
public class Customer : Subject
{
public Customer(string foodName)
{
base.FoodName = foodName;
}
/// <summary>
/// 订餐方法 此方法将触发观察者的一系列动作
/// </summary>
public void OrderMeal()
{
Console.WriteLine("顾客:我要一份{0}", base.FoodName);
base.Notify();
}
}


测试:

class Program
{
static void Main(string[] args)
{
Customer customer = new Customer("西红柿鸡蛋汤面");
Waiter waiter = new Waiter(customer);
Cook cook = new Cook(customer);
//订餐 动作
customer.OrderMeal();
Console.Read();
}
}


结果:



观察者模式适用场景

当一个对象的数据更新时需要通知其他对象,但这个对象又不希望和被通知的那些对象形成紧耦合。
当一个对象的数据更新时,这个对象需要让其他对象也各自更新自己的数据,但这个对象不知道具体有多少对象需要更新数据

观察者模式与其他模式的关系

观察者模式与备忘录模式的关系
观察者模式使用了备忘录模式(Memento Pattern),暂时将观察者对象存储在被观察者对象里面
观察者模式与MVC模式的关系
观察者模式可以用来实现MVC模式。观察者模式中的主题便是MVC模式中的模型加控制器,而观察者便是视图
一般情况下,MVC是观察者模式、组合模式、策略模式等设计模式的组合。

总结

观察者模式的有点

1,具体主题和具体观察者是松耦合关系。

由于主题(Subject)接口仅仅依赖于观察者(Observer)接口,因此具体主题只是知道它的观察者是实现观察者(Observer)接口的某个类的实例,但不需要知道具体是哪个类。同样,由于观察者仅仅依赖于主题(Subject)接口,因此具体观察者只是知道它依赖的主题是实现主题(subject)接口的某个类的实例,但不需要知道具体是哪个类。

2,观察者模式满足“开-闭原则”。

主题(Subject)接口仅仅依赖于观察者(Observer)接口,这样,我们就可以让创建具体主题的类也仅仅是依赖于观察者(Observer)接口,因此如果增加新的实现观察者(Observer)接口的类,不必修改创建具体主题的类的代码。同样,创建具体观察者的类仅仅依赖于主题(Observer)接口,如果增加新的实现主题(Subject)接口的类,也不必修改创建具体观察者类的代码。

观察者模式的缺点

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

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

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

参考书

Head First 设计模式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: