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

事件

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

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

模型------视图

发布------订阅

源------收听者

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

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

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

相关推荐
TechWJ15 分钟前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
lly20240638 分钟前
C++ 文件和流
开发语言
m0_7066532344 分钟前
分布式系统安全通信
开发语言·c++·算法
寻寻觅觅☆1 小时前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++
刘欣的博客1 小时前
C# CS架构程序发版升级的走数据库方案
c#·单文件升级自己的方式
lightqjx1 小时前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列
zh_xuan2 小时前
kotlin lazy委托异常时执行流程
开发语言·kotlin
阿猿收手吧!2 小时前
【C++】string_view:高效字符串处理指南
开发语言·c++
玄同7652 小时前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
Yorlen_Zhang3 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#