using System;
namespace Observer
{
/// <summary>
/// 声明一个委托类型
/// </summary>
/// <param name="ringKind">表示铃声种类(1 表示上课铃声;2 表示下课铃声)</param>
public delegate void RingEvent(int ringKind);
class Program
{
static void Main(string[] args)
{
//使用学校打铃实现发布订阅
SchoolRing sr = new SchoolRing();//发布者
Students stu1 = new Students("张三");//订阅者1
Students stu2 = new Students("李四");//订阅者2
//张三订阅铃声委托
stu1.SubscribeToRing(sr);
stu2.SubscribeToRing(sr);
Console.WriteLine("请输入大铃声参数(1:表示上课铃;2:表示下课铃):");
//发布打铃动作
sr.Jow(Convert.ToInt32(Console.ReadLine()));
Console.ReadLine();
}
}
public class SchoolRing:Students
{
public event RingEvent OnbellSound;//委托事件,作为发布者
public void Jow(int ringKind)
{
//if (ringKind == 1 || ringKind == 2)
//{
// Console.Write(ringKind == 1 ? "上课铃响了!" : "下课铃响了!");
//}
if (OnbellSound != null)
{//说明她已订阅了具体的方法
OnbellSound(ringKind);//回调onbellSound委托订阅的具体方法
}
else
{
Console.WriteLine("铃声参数不对,1是上课铃,2是下课铃");
}
}
}
public class Students
{
public string Name { get; set; }
public Students()
{
}
public Students(string name) {
this.Name = name;
}
//订阅事件
private void SchoolJow(int ringKind)
{
if (ringKind == 2)
{
Console.WriteLine("下课铃响了,"+this.Name+"可以休息了!");
}
else if (ringKind == 1)
{
Console.WriteLine("上课铃响了," + this.Name + "认真学习!");
}
}
//学生订阅铃声委托事件
public void SubscribeToRing(SchoolRing school)
{
school.OnbellSound += SchoolJow;
}
public void CancelSubscribe(SchoolRing school) {
school.OnbellSound -= SchoolJow;
}
}
}