首页 > 代码库 > 委托/事件:猫叫鼠跑人醒

委托/事件:猫叫鼠跑人醒

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

namespace CatCryRatRunMasterWake
{
  /// <summary>
  /// define a delegate
  /// </summary>
  public delegate void CatCryEventHandle();

  class Program
  {
    static void Main(string[] args)
    {
      Cat cat = new Cat("Tom");
      Rat rat = new Rat("Jack", cat);
      Master master = new Master("Ls", cat);
      cat.Cry();

      Console.ReadKey();
    }
  }

  /// <summary>
  /// define a cat objects
  /// </summary>
  public class Cat
  {
    private string _name;

    //define a cat cry event
    public event CatCryEventHandle WhenCatCry;

    public Cat(string name)
    {
    _name = name;
      }

    public void Cry()
    {
      this.WhenCatCry();
      Console.WriteLine("猫叫!");
    }
  }

  /// <summary>
  /// define a rat objects
  /// </summary>
  public class Rat
  {
    private string _name;
    public Rat(string name, Cat cat)
    {
      _name = name;
      cat.WhenCatCry += Run; //订阅猫叫事件
    }

    public void Run()
    {
      Console.WriteLine("老鼠跑!");
    }
  }

  /// <summary>
  /// define a master objects
  /// </summary>
  public class Master
  {
    private string _name;
    public Master(string name, Cat cat)
    {
      _name = name;
      cat.WhenCatCry += WakeUp; //订阅猫叫事件
    }

    public void WakeUp()
    {
      Console.WriteLine("主人醒!");
    }
  }
}

委托/事件:猫叫鼠跑人醒