zoukankan      html  css  js  c++  java
  • 23种设计模式之观察者模式(Observer)

    观察者模式又称为发布—订阅模式、模型—视图模式、源-监听器模式或从属者(dependents)模式,是一种对象的行为型模式。它定义了对象之间的一种一对多的依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象都得到通知并被自动更新。观察者模式的优点在于实现了表示层和数据层的分离,并定义了稳定的更新消息传递机制,类别清晰,抽象了更新接口,使得相同的数据层可以有各种不同的表示层。

    优点:

    1)抽象了主体与Observer之间的耦合关系。

    2)支持广播方式的通信。

    使用场景:

    1)对一个对象的修改涉及对其它对象的修改,而且不知道有多少对象需要进行相应修改。

    2)对象应该能够在不用假设对象标识的前提下通知其它对象。

     

    public interface Observer  
    {  
        void Update(Subject subject);  
    }  
    public interface Subject  
    {  
        void Attach(Observer docExplorer);  
        void Detach(Observer docExplorer);  
        void NotifyObservers();  
    }  
    public class DocExplorer : Observer  
    {  
        public void Update(Subject subject)  
        {  
            Console.WriteLine("更新DocExplorer自身的状态");  
        }  
    } 
    /// <summary>  
    /// 公文类  
    /// </summary>  
    public class OfficeDoc : Subject  
    {  
        //存储与OfficeDoc相关联的DocExplorer对象  
        private IList<Observer> observerList = new List<Observer>();  
      
        /// <summary>  
        /// 将某DocExplorer对象与OfficeDoc相关联  
        /// </summary>  
        /// <param name="docExplorer"></param>  
        public void Attach(Observer docExplorer)  
        {  
            observerList.Add(docExplorer);  
        }  
      
        /// <summary>  
        /// 解除某DocExplorer对象与OfficeDoc的关联关系  
        /// </summary>  
        /// <param name="docExplorer"></param>  
        public void Detach(Observer docExplorer)  
        {  
            observerList.Remove(docExplorer);  
        }  
      
        /// <summary>  
        /// 通知所有的DocExplorer对象  
        /// </summary>  
        public void NotifyObservers()  
        {  
            IEnumerator enumeration = observerList.GetEnumerator();  
            while (enumeration.MoveNext())  
            {  
                Observer observer = enumeration.Current as Observer;  
                observer.Update(this);  
            }  
        }  
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            //观察者设计模式  
            Subject subject = new OfficeDoc();  
            Observer doc = new DocExplorer();  
            subject.Attach(doc);  
            subject.Attach(doc);  
            subject.Attach(doc);  
            subject.NotifyObservers();  
        }  
    }  

  • 相关阅读:
    LeetCode 10. Regular Expression Matching
    LeetCode 5. Longest Palindromic Substring
    LeetCode 67. Add Binary
    LeetCode 8. String to Integer (atoi)
    学习笔记之C++ Primer中文版(第五版)
    LeetCode 13. Roman to Integer
    学习笔记之Macbook
    腾讯//LRU缓存机制
    腾讯//LRU缓存机制
    腾讯//子集
  • 原文地址:https://www.cnblogs.com/guwei4037/p/6689469.html
Copyright © 2011-2022 走看看