观察者模式允许你定义一种订阅机制,可在对象事件发生时,通知多个 “观察” 该对象的其他对象
观察者模式定义的是一种一对多的关系:
如下图所示,每次到货都要发邮件给各家各户
用观察者模式解决问题:商店浪费资源去通知没有需求的客户
✔ 优点 | ❌ 缺点 |
---|---|
无需修改发布者代码就能引入新的订阅者类 (如果是发布者接口则可轻松引入发布者类) | 订阅者的通知顺序是随机的 |
可以在运行时建立对象之间的联系 |
Program:
namespace Observer
{
class Program
{
static void Main(string[] args)
{
Subject subject = new Subject();
ObserverA observerA = new ObserverA();
ObserverB observerB = new ObserverB();
subject.Attach(observerA);
subject.Attach(observerB);
subject.SomeBusinessLogic();
subject.SomeBusinessLogic();
subject.Detach(observerA);
subject.SomeBusinessLogic();
}
}
}
IObserver:
namespace Observer
{
interface IObserver
{
public void Update(ISubject subject) { }
}
}
ObserverA:
using System;
namespace Observer
{
class ObserverA: IObserver
{
public void Update(ISubject subject)
{
if ((subject as Subject).state > 2)
{
Console.WriteLine("ObserverAAA Update ... state: " + (subject as Subject).state.ToString());
}
}
}
}
ObserverB:
using System;
namespace Observer
{
class ObserverB:IObserver
{
public void Update(ISubject subject)
{
if((subject as Subject).state > 0 && (subject as Subject).state < 3)
{
Console.WriteLine("ObserverBBB Update ... state: " + (subject as Subject).state.ToString());
}
}
}
}
ISubject:
namespace Observer
{
interface ISubject
{
public void Attach(IObserver observer) { }
public void Detach(IObserver observer) { }
public void Notify() { }
}
}
Subject:
using System;
using System.Collections.Generic;
using System.Threading;
namespace Observer
{
class Subject: ISubject
{
public int state;
private List<IObserver> observerList = new List<IObserver>();
public void Attach(IObserver observer)
{
if (observer != null)
{
observerList.Add(observer);
}
}
public void Detach(IObserver observer)
{
if (observer != null)
{
observerList.Remove(observer);
}
}
public void Notify()
{
foreach (var observer in observerList)
{
observer.Update(this);
}
}
public void SomeBusinessLogic()
{
Console.WriteLine("Subject do SomeBusinessLogic");
state = new Random().Next(0, 10);
Thread.Sleep(15);
Console.WriteLine("Subject SomeBusinessLogic state: " + state.ToString());
Notify();
}
}
}
F5 运行结果:
Subject do SomeBusinessLogic
Subject SomeBusinessLogic state: 8
ObserverAAA Update … state: 8
Subject do SomeBusinessLogic
Subject SomeBusinessLogic state: 0
Subject do SomeBusinessLogic
Subject SomeBusinessLogic state: 1
ObserverBBB Update … state: 1
参考:观察者模式