using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//行为型-观察者模式、基于事件的观察者
namespace Chap2_2
{
public class Observer
{
Employee emp = EmployeeFactory.CreateEmployee("Alfred_Xu", "南京、成都", EmployeeFactory.addressFactory);
public void testObserver()
{
emp.EmployeeChangenameEvent += Employee.employee_EmployeeChangeNameEvent;//订阅事件,定义事件触发后,由谁来做什么
emp.ChangeName("Alfred.Xu");
Console.ReadKey();
}
public void testObserver2()
{
emp.EmployeeChangenameEvent += empChangeName;//订阅事件
emp.ChangeName("Alfred.Xu");
Console.ReadKey();
}
public void empChangeName(string name)
{
Console.WriteLine("修改后的名称;" + name);
}
public void show()
{
Console.WriteLine(string.Format("员工名:{0}", emp.Name));
Console.WriteLine(string.Format("户籍地:{0}", emp.AddressCollection.Address1));
Console.WriteLine(string.Format("工作地:{0}", emp.AddressCollection.Address2));
}
}
public partial class Employee
{
//定义委托
public delegate void EmployeeChangedName(string ChangedName);
//创建委托对象
private EmployeeChangedName employeeChangedName;
//具体的事件
public event EmployeeChangedName EmployeeChangenameEvent
{
add { employeeChangedName += value; }
remove { if (employeeChangedName != null) { employeeChangedName -= value; } }
}
//该方法执行时,触发事件
public void ChangeName(string name)
{
this.Name = name;
this.employeeChangedName(name);//事件只有在对象内部才能触发
}
//事件的具体执行,方法与上面的委托一致
static public void employee_EmployeeChangeNameEvent(string ChangeName)
{
Console.WriteLine("修改后的名称;"+ChangeName);
}
}
}