• 设计模式》观察者模式


    例子

    教会(Subject)
    教会成员(Observer)

    public class GuildSubject
        {
            private List<AbsSubscriber<GuildSubject>> _subscribers;
    
            public GuildSubject(string guildName)
            {
                GuildName = guildName;
                _subscribers = new List<AbsSubscriber<GuildSubject>>();
            }
    
            public void AddObserver(AbsSubscriber<GuildSubject> obj)
            {
                _subscribers.Add(obj);
            }
    
            public void RemoveObserver(AbsSubscriber<GuildSubject> obj)
            {
                _subscribers.Remove(obj);
            }
    
            public void SendData(string data)
            {
                foreach (var subscriber in _subscribers)
                {
                    subscriber.ReceiveData(this, data);
                }
            }
    
    
            public string GuildName { get; }
        }
    
        public interface IObserver<Subject>
        {
            void ReceiveData(Subject subject, string data);
        }
    
        public abstract class AbsSubscriber<Subject> : IObserver<Subject>
        {
            public AbsSubscriber(string name)
            {
                Name = name;
            }
    
            public string Name { get; }
    
            public abstract void ReceiveData(Subject subject, string data);
        }
    
        public class GuildSubscriber : AbsSubscriber<GuildSubject>
        {
            public GuildSubscriber(string name) : base(name)
            {
            }
    
            public override void ReceiveData(GuildSubject subject, string data)
            {
                Console.WriteLine($"{this.Name}收到{subject.GuildName}教会的消息:{data}");
            }
        }
    
            private static void SubjectTest()
            {
                var guildSubject = new GuildSubject("牛逼教会");
    
                guildSubject.AddObserver(new GuildSubscriber("信徒1"));
                guildSubject.AddObserver(new GuildSubscriber("信徒2"));
                guildSubject.AddObserver(new GuildSubscriber("信徒3"));
    
                guildSubject.SendData("牛逼起来啦");
            }
    
    
  • 相关阅读:
    Android连载7-动语添加碎片
    JavaScript连载6-转化为Number和Boolean类型、运算符
    Java连载111-timer定时器、反射机制概述
    用conda创建虚拟环境的一些常用命令
    Java内存分析
    Java语言中的Class类
    线程协作
    LeetCode刷题笔记第26题
    LeetCode刷题笔记第20题(括号匹配)
    LeetCode刷提笔记第1332题
  • 原文地址:https://www.cnblogs.com/icxldd/p/15804205.html
Copyright © 2020-2023  润新知