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

事件

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

所以取消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();
        }
    }
    
}
观察者模式

模型------视图

发布------订阅

源------收听者

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

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

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

相关推荐
万邦科技Lafite几秒前
淘宝海外采购指南,taoworld资格申请对接流程讲解
开发语言·电商开放平台·淘宝开放平台·京东开放平台·比价
ThornArmor11 分钟前
奔腾的呼吸:被驱逐者的灵感
开发语言·程序人生·架构
软件黑马王子20 分钟前
12.缓存池优化:对象上限
开发语言·前端框架·c#
阿里嘎多学长22 分钟前
2026-09-07 GitHub 热点项目精选
开发语言·程序员·github·代码托管
流浪00140 分钟前
大模型技术全景(六):AI 的“逐字接龙“——Token 与自回归生成背后的真相
开发语言·人工智能·llm
Raas1001 小时前
AI网关和OpenRouter区别?MAI Gateway(魔芋企业级AI网关)企业级方案对比指南
大数据·开发语言·人工智能·gateway·php·ai网关·mai gateway
点心的游戏开发世界9 小时前
GDScript 入门笔记(十一):Lambda 与匿名函数
开发语言·笔记·游戏引擎·godot
事圆则缓11 小时前
Kotlin 协程完全指南
开发语言·kotlin
我爱写代码i11 小时前
BeLink - 支持生成多种URL 缩短网址PHP源码
开发语言·php·短网址php源码
Java后端的Ai之路11 小时前
20、Python - 备忘录模式
开发语言·人工智能·python·外观模式·备忘录模式