今天又看了下.NET 下的委托与事件,从应用场景的角度重新想了一下,下面将这个记录下来:

现在先假设场景:

1.有一个气象台负责播报下雨。

2.一些需要步行上班的人,听到气象台预报下雨后要打伞上班。

3.一些骑车上班的人,听到预报下雨后要披雨披上班。

用委托和事件实现:

我的思路:

1.先定义一个气象台:

//气象台
public class WeatherStation
{
    //定义要下雨委托
    public delegate void WillRain();
    //实例委托
    public WillRain willRainDel;
}

 

2.定义走路上班的人和骑车上班的人:

//走路上班的人
public class WalkMan
{
    //监听天气预报
    public WalkMan(WeatherStation weatherSta)
    {
        //广播下雨时,要打伞
        weatherSta.willRainDel += TakeUmbrella;
    }

    //打伞
    public void TakeUmbrella()
    {
        Console.WriteLine("It will rain, I take umbrella.");
    }
}

//骑车上班的人
public class BikeMan
{
    //监听天气预报
    public BikeMan(WeatherStation weatherSta)
    {           
        //广播下雨时,要穿雨披
        weatherSta.willRainDel += TakePoncho;
    }

    //穿雨披
    public void TakePoncho()
    {
        Console.WriteLine("It will rain,I wear poncho.");
    }
}

 

现在来实例化气象台和走路与骑车的人,再来实现气象台播报下雨,走路的人打伞,骑车的人穿雨披:

 

static void Main(string[] args)
{
    //实例化气象台
    WeatherStation ws = new WeatherStation();
    //声明一个走路的人,并订阅气象台预报
    WalkMan Jason = new WalkMan(ws);
    //声明一个骑车的人,并订阅气象台预报
    BikeMan Tony = new BikeMan(ws);
    //气象台播报下雨
    ws.willRainDel();

    Console.Read();
}

 

这是执行程序就会得到这样的结果:

image

 

这个场景用委托就实现了,下面介绍用事件来实现,只需修改气象台类的委托实例替换为事件,同时类里来声明一个方法,调用这个事件。

 

//气象台
public class WeatherStation
{
    //定义要下雨委托
    public delegate void WillRain();
    //委托实例
    //public WillRain willRainDel;

   

       //Event来实现
        public event WillRain willRainEvent;
        public void WillRainTomorrow()
        {
            willRainEvent();
        }

}

 

走路的人和骑车的人也要进行相应的变化,因为委托实例已经被替换掉:

 

//走路上班的人
    public class WalkMan
    {
        //监听天气预报
        public WalkMan(WeatherStation weatherSta)
        {
            //广播下雨时,要打伞
            weatherSta.willRainEvent += TakeUmbrella;
        }

        //打伞
        public void TakeUmbrella()
        {
            Console.WriteLine("It will rain, I take umbrella.");
        }
    }

    //骑车上班的人
    public class BikeMan
    {
        //监听天气预报
        public BikeMan(WeatherStation weatherSta)
        {           
            //广播下雨时,要穿雨披
            weatherSta.willRainEvent += TakePoncho;
        }

        //穿雨披
        public void TakePoncho()
        {
            Console.WriteLine("It will rain,I wear poncho.");
        }
    }

 

这时在实现上面的场景时,main函数就变为:

    static void Main(string[] args)
    {
        //实例化气象台
        WeatherStation ws = new WeatherStation();
        //声明一个走路的人,并订阅气象台预报
        WalkMan Jason = new WalkMan(ws);
        //声明一个骑车的人,并订阅气象台预报
        BikeMan Tony = new BikeMan(ws);
        //气象台播报下雨
        //ws.willRainDel();
        //气象台播报下雨
        ws.WillRainTomorrow();

        Console.Read();
    }
}

将调用委托实例来预报天气变为直接调用方法来预报天气,运行结果是一样的:

image

posted on 2010-05-08 23:21  Read  阅读(390)  评论(1编辑  收藏  举报