委托的注册及注销+观察者模式

事件

委托变量如果公开出去,很不安全,外部可以随意调用

所以取消public,封闭它,我们可以自己书写两个方法,供外部注册与注销,委托调用在子方法里调用,这样封装委托变量可以使它更安全,这个就叫做事件

1.外部不能随便调用,只能注册和注销

2.只能自己去调用自己的委托

委托练习题:

老师会在下课时打铃(事件)

学生们想在打铃事件发生的时候做自己的事情:

小明想在打铃的时候去买东西吃,

小张想在打铃时去打水,

小红想在打铃时开始练习,

小花想在打铃时去打羽毛球。

代码如下:

cs 复制代码
using System;

namespace 事件
{
    public delegate void CallDelegate();
    class Teacher
    {
        public string name;
        CallDelegate callDel;

        public void RegisterCallEvent(CallDelegate del)
        {
            callDel += del;
        }
        public void LogoutCallEvent(CallDelegate del)
        {
            callDel -= del;
        }
        public Teacher(string name)
        {
            this.name = name;
        }
        public void Call()
        {
            Console.WriteLine("{0}打铃了!",name);
            if (callDel != null)
            {
                callDel();
            }

        }

    }
    class Student
    {
        public string name;
        public string action;
        public Student(string name, string action)
        {
            this.name = name;
            this.action = action;
        }
        public void DoThing()
        {
            Console.WriteLine(name + action);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Teacher teacher = new Teacher("王老师");
            Student xiaoming = new Student("小明", "买东西吃");
            Student xiaozhang = new Student("小张", "打水");
            Student xiaohong = new Student("小红", "练习");
            Student xiaohua = new Student("小花", "打羽毛球");

            //teacher.callDel = xiaoming.DoThing;
            //teacher.callDel += xiaozhang.DoThing;
            //teacher.callDel += xiaohong.DoThing;
            //teacher.callDel += xiaohua.DoThing;

            //teacher.Call();
            teacher.RegisterCallEvent(xiaoming.DoThing);
            teacher.RegisterCallEvent(xiaozhang.DoThing);
            teacher.RegisterCallEvent(xiaohong.DoThing);
            teacher.RegisterCallEvent(xiaohua.DoThing);

            teacher.Call();
        }
    }
    
}
观察者模式

模型------视图

发布------订阅

源------收听者

一系列对象来监听另外一个对象的行为,被监听者一旦触发事件/发布消息,则被所有监听者收到,然后执行自己的行为。

就是使用委托/事件,让一系列对象把他们的行为来注册到我的委托中去。

该系列专栏为网课课程笔记,仅用于学习参考。

相关推荐
唐青枫1 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20107 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools21 小时前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5