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

事件

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

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

模型------视图

发布------订阅

源------收听者

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

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

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

相关推荐
武子康5 小时前
Java-171 Neo4j 备份与恢复 + 预热与执行计划实战
java·开发语言·数据库·性能优化·系统架构·nosql·neo4j
怪兽20146 小时前
fastjson在kotlin不使用kotlin-reflect库怎么使用?
android·开发语言·kotlin
ClearLiang6 小时前
Kotlin-协程的挂起与恢复
开发语言·kotlin
彭同学学习日志6 小时前
Kotlin Fragment 按钮跳转报错解决:Unresolved reference ‘floatingActionButton‘
android·开发语言·kotlin
海域云赵从友6 小时前
破解跨境数据传输瓶颈:中国德国高速跨境组网专线与本地化 IP 的协同策略
开发语言·php
咚咚王者7 小时前
人工智能之编程进阶 Python高级:第九章 爬虫类模块
开发语言·python
深蓝海拓7 小时前
使matplot显示支持中文和负号
开发语言·python
syt_biancheng8 小时前
Day3算法训练(简写单词,dd爱框框,3-除2!)
开发语言·c++·算法·贪心算法
864记忆8 小时前
Qt Network 模块中的函数详解
开发语言·网络·qt
864记忆8 小时前
Qt Sql 模块中的函数详解
开发语言·网络·qt