概念
观察者模式定义类一种一对多的依赖关系,让多个观察者对象同事监听某一个主体对象,这个主题对象在状态发生变化时,会通知所有的观察者对象,是他们能够自动更新
优点:
观察者模式解除了主题和具体观察者的耦合,让耦合的双方都依赖于抽象,而不是依赖具体。从而使得各自的变化都不会影响另一边的变化。
缺点:
依赖关系并未完全解除,抽象通知者依旧依赖抽象的观察者。
适用场景
当一个对象的改变需要给变其它对象时,而且它不知道具体有多少个对象有待改变时。
一个抽象某型有两个方面,当其中一个方面依赖于另一个方面,这时用观察者模式可以将这两者封装在独立的对象中使它们各自独立地改变和复用。
实例1
效果图:
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 烧开水.Observer;
namespace 烧开水
{
class Program
{
static void Main(string[] args)
{
Heater heater= new Heater();
heater.BoildEvent += new AlermMachine().Alerm;//绑定警报器
heater.BoildEvent += new DisplayMachie().ShowTemperature;//绑定显示温度的方法
//水烧开了,触发事件
heater.BoildWater();
Console.ReadKey();
}
}
}
Heater
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 烧开水
{
/// <summary>
/// 热水器
/// </summary>
public class Heater
{
/// <summary>
/// 水温
/// </summary>
private int _temperature;
/// <summary>
/// 水烧开的事件
/// </summary>
public event Action<int> BoildEvent;
/// <summary>
/// 烧水
/// </summary>
public void BoildWater()
{
try
{
for (int i = 0; i < 100; i++)
{
_temperature = i;
//当水烧开
if (_temperature >= 95)
{
BoildEvent(_temperature);
}
}
}
catch (Exception exception)
{
throw exception;
}
}
}
}
Observer:
DisplayMachie
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 烧开水.Observer
{
/// <summary>
/// 显示器
/// </summary>
public class DisplayMachie
{
/// <summary>
/// 显示温度
/// </summary>
public void ShowTemperature(int temperature)
{
Console.WriteLine($"当前温度是{temperature}C");
}
}
}
AlermMachine
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 烧开水.Observer
{
/// <summary>
/// 警报器
/// </summary>
public class AlermMachine
{
/// <summary>
/// 发出警报
/// </summary>
public void Alerm(int temperature)
{
Console.WriteLine("我发出警报了");
}
}
}