观察者模式 C#

用C#实现观察者模式:用委托和事件

 

代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    
public class Cat
    {
        
private string name;
        
public string Name
        {
            
get { return name; }
        }
        
public delegate void CatShoutEventHandler(Object sender,CatShoutEventArgs args); //声明委托
        public event CatShoutEventHandler CatShout; //声明事件
        public Cat(string name)
        {
            
this.name = name;
        }
        
//事件参数
        public class CatShoutEventArgs : EventArgs
        {
            
private  string sound;
            
public string Sound
            {
                
get { return sound;}
            }
            
public CatShoutEventArgs(string sound)
            {
                
this.sound = sound;
            }
        }

        
protected virtual void OnShout(CatShoutEventArgs e)
        {
            
if (CatShout != null)
            {
                CatShout(
this,e);
            }
        }

        
public void shout()
        {
            
if (this.Name == "jack")
            {
                CatShoutEventArgs e 
= new CatShoutEventArgs("large sound");
                OnShout(e);
            }
        }

    }
    
public class Mouse
    {
        
private string name;
        
public string Name
        {
            
get { return name;}
        }
        
public Mouse(){
        }
        
public Mouse(string name) {
            
this.name = name;
        }
        
public static void ShowMsg(Object sender, Cat.CatShoutEventArgs e)
        {   
//静态方法
            Cat cat = (Cat)sender;
            Console.WriteLine(
"有只猫,它的名字是:{0} 没有名字 快跑: ", cat.Name);
            Console.WriteLine(
"它的声音:"+e.Sound);
            Console.WriteLine();
        }

        
public  void ShowMsgWithName(Object sender, Cat.CatShoutEventArgs e)
        {  
       Cat cat = (Cat)sender;
            Console.WriteLine(
"有只猫,它的名字是:{0} 小老鼠{1} 快跑: ", cat.Name,this.Name);
            Console.WriteLine(
"它的声音:" + e.Sound);
            Console.WriteLine();
        }

    }
    
class Program
    {
        
static void Main()
        {
            Cat cat
= new Cat("jack");
            Mouse mouse 
= new Mouse("jim");

            cat.CatShout 
+= Mouse.ShowMsg;  //注册静态方法
            cat.CatShout += (new Mouse("tom")).ShowMsgWithName;  //给匿名对象注册方法
            cat.CatShout += new Cat.CatShoutEventHandler(mouse.ShowMsgWithName);
            cat.shout();   
//猫叫,会自动调用注册过对象的方法
            Console.ReadLine();
        }
    }

}
输出:

有只猫,它的名字是:jack 没有名字 快跑:
它的声音:large sound

有只猫,它的名字是:jack 小老鼠tom 快跑:
它的声音:large sound

有只猫,它的名字是:jack 小老鼠jim 快跑:
它的声音:large sound


 

 

posted on 2010-03-10 09:02  孟凡龙  阅读(176)  评论(0)    收藏  举报