观察者模式

本节主要内容: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代码:

View Code
 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代码:

View Code
 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

View Code
 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

 

转载于:https://www.cnblogs.com/xyz168/archive/2011/11/30/2268667.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值