• 观察者模式(Observer Pattern)


    观察者模式:定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主体对象,这个主题对象在状态发生变化时,会通知所有观察者。当一个对象改变需要同时改变其他对象,而且他不知道具体有多少对象需要改变的时候,应该考虑使用观察者模式。

    Define a one-to-many dependency between objects so that when one objects changes state,all its dependents are notified and updated automatically.

    观察者结构图:

    代码:

        public abstract class Subject
        {
            private IList<Observer> observers = new List<Observer>();
    
            public void Attach(Observer observer)
            {
                observers.Add(observer);
            }
    
            public void Detach(Observer observer)
            {
                observers.Remove(observer);
            }
    
            public void Notify()
            {
                foreach (Observer o in observers)
                {
                    o.Update();
                }
            }
        }
    
        public abstract class Observer
        {
            public abstract void Update();
        }
    
        public class ConcreteSubject : Subject
        {
            private string subjectState;
            public string SubjectState
            {
                get { return subjectState; }
                set { subjectState = value; }
            }
        }
    
        public class ConcreteObserver : Observer
        {
            private string name;
            private string observerState;
            private ConcreteSubject subject;
            public ConcreteSubject Subject
            {
                get { return subject; }
                set { subject = value; }
            }
            public ConcreteObserver(ConcreteSubject subject, string name)
            {
                this.subject = subject;
                this.name = name;
            }
    
            public override void Update()
            {
                observerState = subject.SubjectState;
                Console.WriteLine("观察者{0}的新状态是{1}",name,observerState);
            }
        }

    引用:

                ConcreteSubject c = new ConcreteSubject();
                c.Attach(new ConcreteObserver(c, "A"));
                c.Attach(new ConcreteObserver(c, "b"));
                c.Attach(new ConcreteObserver(c, "z"));
                c.SubjectState = "ABC";
                c.Notify();

    效果

  • 相关阅读:
    codeblocks 缺少dll libstdc++-6.dll and so on
    gtx 1650 inspiron 1501 pytouch env
    python串口通信
    devops tools
    mosquitto 消息持久化到file
    Mybatis mapper动态代理的原理详解(转)
    Java @Repeatable(转)
    Linux进阶教程丨第10章:管理网络
    CTF-Pwn丨栈溢出入门题目思路解析
    白帽专访丨月神:我的The loner安全团队
  • 原文地址:https://www.cnblogs.com/nygfcn1234/p/3408989.html
Copyright © 2020-2023  润新知