zoukankan      html  css  js  c++  java
  • 观察者模式(委托事件的小应用)

    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();
            }
        }
    }
  • 相关阅读:
    Python 操作Redis 转载篇
    Django运行SQL语句
    将博客搬至CSDN
    MySQL学习(三)函数
    MySQL学习(二)数据类型
    MySQL学习(一) 数据表基本操作
    Django聚合函数
    windows平台上编译mongdb-cxx-driver
    小程序登陆遇到 ERR_REQUEST_PARAM
    Opengrok服务器搭建step by step
  • 原文地址:https://www.cnblogs.com/FangZhaohu/p/5070453.html
Copyright © 2011-2022 走看看