程序设计:猫叫,老鼠跑,主人醒。用事件加代理模式实现,要有联动性,老鼠和主人的行为是被动的,考虑猫叫可引起其他联动效应
最好是用C#写,

解决方案 »

  1.   

    http://community.csdn.net/Expert/topic/3829/3829507.xml?temp=.2119409这里有个例子。
      

  2.   

    this is the observer pattern, a typical implementation in .NET is to use event, for exampleusing System;class Cat
    {
      public event EventHandler Mew;  protected virtual void OnMew (EventArgs e)
      {
    if (Mew != null)
      Mew(this,e);
      }  public void DoMew()
      {
    Console.WriteLine("Cat mewed, raising an event...");
    OnMew(EventArgs.Empty);
      }
    }class Mouse
    {
      public void Run()
      {
    Console.WriteLine("Mouse ran...");
      }  public void OnCatMew(Object sender, EventArgs e)
      {
    Console.WriteLine("Mouse heard the cat mewed...");
    Run();
      }
    }class Owner
    {
      public void Awake()
      {
    Console.WriteLine("Owner awoke..");
      }  public void OnNoise(Object sender, EventArgs e)
      {
    if (sender is Cat)
    Console.WriteLine("Owner heard the cat mewed....");
    else
    Console.WriteLine("Owner heard some other noise...");
    Awake();
      }
    }class TestMew
    {
      public static void Main()
      {
    Cat c = new Cat();
    Mouse m = new Mouse();
    Owner o = new Owner(); c.Mew += new EventHandler(m.OnCatMew);
    c.Mew += new EventHandler(o.OnNoise); c.DoMew();
      }
    }
      

  3.   

    给你个中文的..参考参考先..using System;namespace MyEventHandler
    {
    /// <summary>
    /// Class2 的摘要说明。
    /// </summary>
    /// 
    public delegate void maojiao(object sender,EventArgs e);

    public class mao{
    public event maojiao mj;
    private void maod(EventArgs e){
    if(mj!=null){
    mj(this,e);
    }
    }
    public void maoj(){
    Console.WriteLine("猫开始叫");
    mj(this,EventArgs.Empty);
    }
    }

    public class laoshu{
    public void laoshup(){
    Console.WriteLine("老鼠跑\n=========================");
    }

    public void laoshupp(object sender,EventArgs e){
    if(sender is mao)
    {
    Console.WriteLine("猫叫事件触发了:");
    }
    else{
    Console.WriteLine("其他事件触发了:");
    }
    laoshup();
    } } public class ren{
    public void renj(){
    Console.WriteLine("人动\n=========================");
    } public event EventHandler rz;
    public void rzz(){
    Console.WriteLine("人自己的事件");
    if(rz!=null){
    rz(this,EventArgs.Empty);
    }
    } public void renjj(object sender,EventArgs e){
    if(sender is mao)
    {
    Console.WriteLine("猫叫事件触发了:");
    }
    else
    {
    Console.WriteLine(sender.ToString().Split('.')[1]+"事件触发了:");
    }
    renj();
    } } public class Class2
    {
    static void Main(string[] args) 
    {
    mao m = new mao();
    ren r = new ren();
    laoshu l = new laoshu();
    m.mj += new maojiao(r.renjj);
    m.mj += new maojiao(l.laoshupp);
    m.maoj();

    r.rz += new EventHandler(r.renjj);
    r.rzz();
    Console.ReadLine();
    }
    }
    }
      

  4.   

    saucer gave a good e.g. ,thanks!