大话设计模式之观察者模式

转载地址:

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

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

View Code

 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

View Code

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();
         }
     }
 }

运行结果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值