委托与事件,两个饮水机。
当饮水机没水了,饮水机会通知人去换水(这是智能饮水机)
using System;
using System.Collections.Generic;
using System.Text;
namespace warteringTrough
{
class Program
{
static void Main(string[] args)
{
int w1 = 3;
int w2 = 2;
warteringTrough wt1 = new warteringTrough("number1", w1);//饮水机
warteringTrough wt2 = new warteringTrough("number2", w2);//饮水机
people me = new people("syler");//一个人
wt1.waterOutHandler += me.fillWater;
wt2.waterOutHandler += me.fillWater;
for (int i = 0; i < w1; i++)
wt1.flowOut();//1号饮水机的水逐渐减少
for (int i = 0; i < w2; i++)
wt2.flowOut();//2号饮水机的水也逐渐减少
}
}
public class warteringTrough
{
public warteringTrough(string identity, int water)
{
this._identity = identity;
this._waterNum = water;
}
private int _waterNum = 0;
private string _identity = string.Empty;
public string Size
{
get { return _identity; }
}
public delegate void waterOut(object sender, flowingEventArgs e);
public event waterOut waterOutHandler;
public int WaterNum
{
get { return _waterNum; }
set { _waterNum = value; }
}
public void flowOut()
{
_waterNum--;
Console.WriteLine("{1}:someone is getting the water, there is {0} left...", _waterNum, _identity);
whenWaterIsflowing();
}
public void whenWaterIsflowing()
{
if (waterOutHandler != null)
{
waterOutHandler(this, new flowingEventArgs(_waterNum));
}
}
}
/*
* 假设有两台饮水机,当没水时会通知人去装水。
*/
public class flowingEventArgs : EventArgs
{
private readonly int _waterNum = 0;
public int WaterNum
{
get { return _waterNum; }
}
public flowingEventArgs(int water)
{
_waterNum = water;
}
}
public class people
{
private string _name = string.Empty;
public people(string name)
{
_name = name;
}
public void fillWater(object sender, flowingEventArgs e)
{
Console.WriteLine("{0}:there is {1} water in the water trough.", _name, e.WaterNum);//可以从这里得到感兴趣的参数,比如水还剩多少
if (e.WaterNum == 0)
{
warteringTrough wt = (warteringTrough)sender;//也可以在这里得到饮水机
Console.WriteLine("{0}:I'm here to deal {1}, so tired a day.", _name, wt.Size);//假设这是饮水机的容量什么的(wt.Size)
}
}
public string Name
{
get { return _name; }
set { _name = value; }
}
}
}





