一.基本简介:观察者设计模式定义了对象间的一种一对多的依赖关系,以便一个对象的状态发生变化时,所有依赖于它的对象都得到通知并自动刷新。在现实生活中的可见观察者模式,例如,微信中的订阅号,订阅博客和QQ微博中关注好友,这些都属于观察者模式的应用。
二.实现:比如热水器在烧水的过程中,当水温即将烧开时,会发出报警的声音,显示器上会出现温度监控
public interface IObserver
{
///
/// 更新自身状态
///
void Update(int temp);
}
///
/// IObserverable接口
///
public interface IObservable
{
///
/// 注册IObserver
///
///
void Register(IObserver obj);
///
/// 取消IObserver的注册
///
///
void Unregister(IObserver obj);
}
///
/// 抽象基类
///
public abstract class SubjectBase:IObservable
{
private List container = new List();
public void Register(IObserver obj)
{
container.Add(obj);
}
public void Unregister(IObserver obj)
{
container.Remove(obj);
}
///
/// 通知所有注册了的Observe
///
protected virtual void Notify(int temp)
{
foreach (IObserver observer in container)
{
//调用Observer的Update()方法
observer.Update(temp);
}
}
}
public class Heater:SubjectBase
{
private int temp;//水温
protected virtual void OnBioiled()
{
base.Notify(temp);
}
public void GetMonitoring()
{
for (int i = 0; i <= 99; i++)
{
temp = i + 1;
if (temp > 95)
{
OnBioiled();
}
}
}
}
public class Alarm:IObserver
{
public void Update(int temp)
{
if (temp == 100)
{
Console.WriteLine("水烧开了"+temp);
}
else
{
Console.WriteLine("开始报警,水快烧开了>> " + temp);
}
}
}
public class Screen:IObserver
{
public void Update(int temp)
{
if (temp == 100)
{
Console.WriteLine("水烧开了" + temp);
}
else
{
Console.WriteLine("水快烧开了>> " + temp);
}
}
}
///
/// C#设计模式-观察者模式
///
class Program
{
static void Main(string[] args)
{
Heater heater = new Heater();
heater.Register(new Screen());
heater.Register(new Alarm());
heater.GetMonitoring();
}
}