快速学习——10、委托、事件-观察者模式(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35030499/article/details/82826727

这篇我们先不讲委托事件,从一些理论来

对象直接的关系

 一对一  :人只有一个身份证号码

一对多:一个人可以有多个号码 (qq号 电话号 车牌号 等)

多对多:多个人 多个号码
 

观察者模式

观察者模式,又称为发布订阅模式,基于一对多的原理。

定义了对象之间的一对多依赖 ,当一个对象改变状态时,它的所有订阅者都会收到通知并自动更新 

举例直播

你订阅了一个主播。 当主播上线直播时,就会通知你。 

  1. 主播任务就是直播,他不知道有谁,多少人订阅他(假设)
  2. 当你订阅主播,只要主播开播,便可以收到主播开播的消息
  3. 有订阅就有取消订阅 (粉转黑)

那我们用代码模拟一下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 委托事件
{
    class Program
    {
        static void Main(string[] args)
        {
            Host h = new Host("贝尔.格里尔斯");    //声明一个主播
            Player p1 = new Player("玩家1");
            Player p2 = new Player("玩家2");
            Player p3 = new Player("玩家3");

            h.AddPlayer(p1);
            h.AddPlayer(p2);
            h.AddPlayer(p3);

            h.StartHost();

            Console.ReadKey();
        }
    }

  
    /// <summary>
    /// 主播
    /// </summary>
    public class Host
    {
        public string hostName;
        public List<Player> playerList = new List<Player>();

        public Host(string hostName)
        {
            this.hostName = hostName;
        }

        /// <summary>
        /// 开播了
        /// </summary>
        public void StartHost()
        {
            Console.WriteLine("我是主播   " + hostName +  "开播了" );
            if(playerList != null && playerList.Count > 0)      //持有list 遍历通知
            {
                foreach (Player p in playerList)
                {
                    p.AccepMessage(hostName);   //通知开播了
                }
            }
        }

        /// <summary>
        /// 添加观众
        /// </summary>
        /// <param name="player"></param>
        public void AddPlayer(Player player)
        {
            this.playerList.Add(player);
        }
    }

    /// <summary>
    /// 玩家 观众
    /// </summary>
    public class Player
    {
        public string playerName;

        public Host host;

        public Player(string playerName)
        {
            this.playerName = playerName;
        }

        /// <summary>
        /// 接受开播了
        /// </summary>
        /// <param name="name"></param>
        public void AccepMessage(string name)
        {
            Console.WriteLine("我是玩家:   " + playerName + "   "  +  "收到了   " + name + "开播了的消息");
        }
    }
}

结果 没有问题 ,主播开播 ,执行通知订阅观众玩家

模拟主播开播了,订阅的收到消息

猜你喜欢

转载自blog.csdn.net/qq_35030499/article/details/82826727