煮水器(.Net中的委托与事件)

热水器类:

 

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

namespace AboutDelegate4
{
    
public class Heater
    {
        
private int temperature;
        
public string type = "REALFIRE 001";
        
public string area = "China";

        
public delegate void BoilEventHandler(object sender, BoilEventArgs e);//委托声明
        public event BoilEventHandler Boiled;//事件声明

        
/// <summary>
        
/// 定义BoiledEventArgs类,传递给Observer所感兴趣的信息
        
/// </summary>
        public class BoilEventArgs:EventArgs
        {
            
public readonly int temperature;
            
public BoilEventArgs(int temperature)//构造函数
            {
                
this.temperature = temperature;
            }
        }

        
/// <summary>
        
/// 煮水函数,在这个函数中调用所有注册的对象的方法
        
/// </summary>
        
/// <param name="e"></param>
        protected virtual void OnBoiled(BoilEventArgs e)
        {
            
if (Boiled!=null)//如果对象有注册
            {
                Boiled(
this, e);//调用所有注册的对象的方法
            }
        }

        
public void BoilWater()
        {
            
for (int i = 0; i <= 100;i++ )
            {
                temperature 
= i;
                
if (temperature>95)
                {
                    BoilEventArgs e 
= new BoilEventArgs(temperature);//建立BoiledEventArgs对象
                    OnBoiled(e);//调用OnBoiled方法
                }
            }
        }

    }
}

 

 

警报器类:

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

namespace AboutDelegate4
{
    
public class Alarm
    {
        
public void MakeAlert(object sender, Heater.BoilEventArgs e)
        {
            Heater heater 
= (Heater)sender;
            Console.WriteLine(
"Alarm:{0}---{1}", heater.area, heater.type);
            Console.WriteLine(
"Alarm:嘟嘟嘟,水已经{0}度了!",e.temperature);
            Console.WriteLine();
        }
    }
}

 

显示器类:

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

namespace AboutDelegate4
{
    
public class Display
    {
        
public static void ShowMsg(object sender,Heater.BoilEventArgs e)
        {
            Heater heater 
= (Heater)sender;
            Console.WriteLine(
"Display:{0}---{1}", heater.area, heater.type);
            Console.WriteLine(
"Display:水已经开了,当前温度为{0}度", e.temperature);
            Console.WriteLine();
        }
    }
}

 

 

posted on 2010-08-03 16:10  晴天1848  阅读(156)  评论(0)    收藏  举报