描述情景:利用代理委托和事件我们处理 老板 员工 包含的动作 买烟 涨工资
实现:老板要抽烟需要买烟会让员工去买烟,然后就给员工涨工资.
Boss
class Boss
{
public delegate void BuySmokeHandle(Boss boss, Employee em);
//定义老板抽烟的事件
public event BuySmokeHandle smokehandler;
public string name;
public Boss()
{
name = "老板";
//注册抽烟事件 交由哪个函数来处理
//调用方式1: 可以注释行 97
// smokehandler += new BuySmokeHandle(smokeevent);
}
public void asksmoke(Employee em)
{
if (this.smokehandler != null)
{
BuySmokeHandle hander = new BuySmokeHandle(em.buysomke);
hander(this, em);
}
}
public virtual void smokeevent(Boss boss,Employee emname)
{
Console.WriteLine("e:{0}给b:{1}买的烟抽完了,{2}你很不错 //事件的使用", emname.name, boss.name,emname.name);
//因此我决定还可以多做一些事情,在抽到烟过后 ,小王 你的工资张拉
emname.slary = 8000;
}
}
Empoyee
class Employee
{
public double slary
{
get; set;
}
public string name
{
get; set;
}
public Employee()
{
name = "员工";
}
public void buysomke(Boss boss,Employee emnamme)
{
Console.WriteLine("e:{0}给b:{1}买了烟 //代理方式让下属买烟",emnamme.name,boss.name);
//让买到烟 老板 就要去抽烟
boss.smokeevent(boss, emnamme);
}
}
调用
Boss boss = new Boss();
boss.name = "张与";
Employee em = new Employee();
em.name = "小王";
//方式2: 可以注释35
boss.smokehandler += new Boss.BuySmokeHandle(boss.smokeevent);
boss.asksmoke(em);
Console.WriteLine("{0}的工资涨到了{1}",em.name, em.slary);
Console.ReadLine();