阅读:        作者:FangZhaohu

观察者模式(委托事件的小应用)

using System;

namespace ObserverDemo
{
    public delegate void RaiseEventHandler(string hand);

    public delegate void FallEventHandler();

    public class A
    {
        public event RaiseEventHandler RaiseEvent;
        public event FallEventHandler FallEvent;

        public void Raise(string hand)
        {
            Console.WriteLine("首领{0}手举杯", hand);
            if (RaiseEvent != null)
            {
                RaiseEvent(hand);
            }
        }

        public void Fall()
        {
            Console.WriteLine("首领A摔杯");
            if (FallEvent != null)
            {
                FallEvent();
            }
        }
    }

    public class B
    {
        private A _a;

        public B(A a)
        {
            _a = a;
            a.FallEvent += FallAttack;
            a.RaiseEvent += RaiseAttack;
        }

        private void FallAttack()
        {
            Console.WriteLine("部下B发起攻击");
        }

        private void RaiseAttack(string hand)
        {
            if (hand == "")
            {
                Console.WriteLine("部下B发起攻击");
            }
        }
    }

    public class C
    {
        private readonly A _a;

        public C(A a)
        {
            _a = a;
            _a.FallEvent += FallAttack;
            _a.RaiseEvent += RaiseAttack;
        }

        private void FallAttack()
        {
            Console.WriteLine("部下C发起攻击");
        }

        private void RaiseAttack(string hand)
        {
            if (hand == "")
            {
                Console.WriteLine("部下C发起攻击");
            }
        }
    }

    internal static class Program
    {
        private static void Main(string[] args)
        {
            var a = new A();
            var b = new B(a);
            var c = new C(a);
            //a.Raise("左");
            //a.Raise("右");
            a.Fall();
            Console.ReadKey();
        }
    }
}

 

Tags: 观察者模式   观察者   观察   模式   应用