head first (二):观察者模式

首先推荐一下别人写的,很不错可以参考,http://www.cnblogs.com/li-peng/archive/2013/02/04/2892116.html

1.定义

观察者模式:在对象之间定义一对多的依赖,当一个对象改变状态时,依赖它的对象都会收到通知并自动更新。

原则:为交互对象之间的松耦合设计而努力

2:使用场景

传统例子,订阅报纸,报纸为主题,订阅者为观察者,当报纸更新时,订阅者就会收到最新的报纸。

3:代码实现

 ★主题(报纸的接口和实现),更新报纸,添加,删除,通知观察者

    interface IPaper
    {
        void UpdatePaper(string Content);

        void RegisterObserver(IMan man);

        void RemoveObserver(IMan man);

        void NotifyObserver(string content);
    }
public class PeoplePaper : IPaper
    {
        private List<IMan> manList;

        public void RegisterObserver(IMan man)
        {
            manList.Add(man);
        }

        public void RemoveObserver(IMan man)
        {
            if (manList.IndexOf(man) >= 0)
            {
                manList.Remove(man);
            }
        }

        public void NotifyObserver(string content) 
        {
            foreach (IMan man in manList)
            {
                man.Update(content);
            }
        }

        public PeoplePaper()
        {
            manList = new List<IMan>();
        }
        public void UpdatePaper(string Content)
        {
            string strContent = "人民日报" + DateTime.Now.ToString() + "发布:" + Content;
            NotifyObserver(strContent);
        }
    }

★观察者接口与实现,接受更新信息

   public interface IMan
    {
        void Update(string content);
    }
    class FirstMan : IMan
    {
        public void Update(string content)
        {
            Console.WriteLine("小明收到了{0}",content);
        }
    }
    class SecondMan : IMan
    {
        public void Update(string content)
        {
            Console.WriteLine("小红收到了{0}", content);
        }
    }

★使用订阅与取消订阅

        static void Main(string[] args)
        {
            PeoplePaper paper = new PeoplePaper();

            FirstMan first = new FirstMan();

            SecondMan second = new SecondMan();

            paper.RegisterObserver(first);
            paper.RegisterObserver(second);

            paper.UpdatePaper("美美的事好假!");

            
            paper.RemoveObserver(first);

            paper.UpdatePaper("云南地震了!");

            Console.ReadKey();

        }

4:思考与小结

山石晓月:

  个人感觉这个例子有点不符合常情了。报纸的订阅或者取消是有人通知报纸商的,而例子中却直接由报纸商发起。如果要恰当的表示中间应该加代理,而不能够用单独的观察者来表示,仅仅个人意见。

bluejance:

这些代码就是
报纸的订阅或者取消是有人通知报纸商的
没有人订阅报纸商发的什么报纸。
可能是我的第一个图画的不好,让你有点误解了

山石晓月:

呵呵,你这发起者明明就是 报纸么....

  其实实现和别人的一样,但是我觉得有必要自己写一下代码。上面推荐文章中有位朋友的问题我也想了好久,最后发现用代理也需要在paper里面加代理,其实这只是理解的问题,人订阅报纸,报纸添加订阅者其实是同一件事,只是在订阅者类中实现订阅,最终还是要在paper更新时找寻所有的订阅者,循环去发送更新。

原文地址:https://www.cnblogs.com/xiaoshuai1992/p/headfirst2.html