设计模式实践-观察者模式

 观察者模式
在一对多的情况下,可以让多绑定到一的事件上。从而实现多个观察者获取通知。

class Program

    {
        public static void Run()
        {
            Husky worker = new Husky();
            Engineer engineer = new Engineer();

            DoorKeeper doorKeeper = new DoorKeeper();

            doorKeeper.Update += worker.Update;
            doorKeeper.Update += engineer.Update;

            doorKeeper.meg = "有人来了!";
            doorKeeper.Notify();

            Console.WriteLine("过了一会");

            Customer customer = new Customer();
            customer.Update += worker.Update;
            customer.Update += engineer.Update_Client_Arrived;

            customer.meg = "我是甲方,来提要求了";
            customer.Notify();
        }
    }

    public abstract class BaseWorker
    {
        public string Name;
        public string Status;
        public virtual void Update(string meg)
        {
            Console.WriteLine(meg + "  "+ Name+ " 返回工作岗位.");
        }
    }

    public class Husky : BaseWorker
    {
        public Husky()
        {
            base.Name = "钻井工人";
            base.Status = "摸鱼";
        }
    }

    public class Engineer : BaseWorker
    {
        public Engineer()
        {
            base.Name = "工程师";
            base.Status = "伏案工作";
        }
        public override void Update(string meg)
        {
            Console.WriteLine(meg + "  " + Name + "  继续工作");
        }

        public void Update_Client_Arrived(string meg)
        {
            Console.WriteLine(meg + "  " + Name + "  出门迎接");
        }
    }

    public abstract class BaseNotifier
    {
        public string meg;
        public delegate void Update_NomalPeople_Event(string meg);
        public event Update_NomalPeople_Event Update;

        public void Notify()
        {
            Update(meg);
        }
    }

    public class DoorKeeper : BaseNotifier
    {
    }

    public class Customer : BaseNotifier
    {
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值