转载地址:
http://www.cnblogs.com/xyz168/archive/2011/11/30/2268667.html
本节主要内容:1、观察者模式意图;2、观察者模式UML图描述;3、举例说明;
一、观察者模式意图:
定义了一种一对多得依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
Define a one-to-many dependency between objects so that one object changes state,all its dependents are notified and updated automatically.
二、UML描述
三、举例说明:
猫叫,主人醒,老鼠跑
Observer代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace y.ObserverPattern { public interface IObserver { void Response(); } public class Host:IObserver { public void Response() { Console.WriteLine("主人醒来!"); } } public class Rat:IObserver { public void Response() { Console.WriteLine("老鼠快跑!"); } } }
Cat代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace y.ObserverPattern
{
class Cat
{
List<IObserver> listObserver = new List<IObserver>();
public void Attach(IObserver observer)
{
listObserver.Add(observer);
}
public void Detach(IObserver observer)
{
listObserver.Remove(observer);
}
public void Meou()
{
Console.WriteLine("猫叫");
foreach (IObserver item in listObserver)
{
item.Response();
}
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace y.ObserverPattern
{
class Program
{
static void Main(string[] args)
{
Console.Title = "观察者模式";
Console.WriteLine("Press any key to exit.......\r\n");
IObserver host = new Host();
IObserver rat = new Rat();
Cat cat = new Cat();
cat.Attach(host);
cat.Attach(rat);
cat.Meou();
Console.Read();
}
}
}
运行结果: