本节主要内容: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代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace y.ObserverPattern
7 {
8 public interface IObserver
9 {
10 void Response();
11 }
12
13 public class Host:IObserver
14 {
15 public void Response()
16 {
17 Console.WriteLine("主人醒来!");
18 }
19 }
20
21 public class Rat:IObserver
22 {
23 public void Response()
24 {
25 Console.WriteLine("老鼠快跑!");
26 }
27 }
28 }
Cat代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace y.ObserverPattern
7 {
8 class Cat
9 {
10 List<IObserver> listObserver = new List<IObserver>();
11 public void Attach(IObserver observer)
12 {
13 listObserver.Add(observer);
14 }
15
16 public void Detach(IObserver observer)
17 {
18 listObserver.Remove(observer);
19 }
20
21 public void Meou()
22 {
23 Console.WriteLine("猫叫");
24 foreach (IObserver item in listObserver)
25 {
26 item.Response();
27 }
28 }
29
30 }
31 }
Program.cs
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace y.ObserverPattern
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 Console.Title = "观察者模式";
13 Console.WriteLine("Press any key to exit.......\r\n");
14 IObserver host = new Host();
15 IObserver rat = new Rat();
16 Cat cat = new Cat();
17 cat.Attach(host);
18 cat.Attach(rat);
19 cat.Meou();
20 Console.Read();
21 }
22 }
23 }
运行结果:
四、源码这里下载
五、参考文献:
《大话设计模式》
http://www.dofactory.com/Patterns/PatternObserver.aspx