“猫叫系统”开启了观察者模式

      眼看着looking for job的日子越来越近,感觉把以前的东西都忘记了,现在仅仅是记得一些基本概念,所以现在必须要拾起来。

      昨天看到了一道面试题,描述如下:猫大叫一声,所有的老鼠都开始逃跑,主人被惊醒。于是想了想,开启了下面的观察者模式:

一、  “猫叫系统”

      银行的防盗系统、高温预警系统、事件处理系统、监控系统,以及这里的“猫叫系统”,其共同特点在于:一个对象的改变会同时影响其他对象做出相应的变化,但是又不知道到底会影响多少个对象。

 

二、  观察者模式

       观察者模式定义了对象之间一对多的依赖关系,当一个对象的状态发生变化时,所有依赖于该对象的其他对象都会被通知,然后自动更新。

       观察者模式中,被观察者管理其它的、依赖于它的观察者对象,当被观察者的状态发生变化时,被观察者会主动发出通知,通知依赖于它的观察者,当观察者收到通知时,会做出相应的动作。

 

三、  “猫叫系统”分析

       下面是该例的具体分析过程:

1、系统中共有3个对象:Cat、Mouse、Human

2、首先,明确一下,哪些对象是观察者,也就是哪些对象需要被通知,哪些对象是被观察者。这里,猫是被观察者,正是由于猫的大叫,才引起后面的一系列反应。

3、当猫大叫的时候,就相当于发出了“警告”,此时,老鼠听到了,然后做出了反应,那就是逃跑。同时,睡梦中的Human也被“警告”吓醒了。

 

四、  观察者模型

 

五、  模式实现

//Subject接口
    public abstract class Subject
    {
        private ArrayList observerList = new ArrayList();

        public void Attach(Observer observer)
        { 
            observerList.Add(observer); 
        }

        public void Detach(Observer observer)
        {
            observerList.Remove(observer); 
        }

        public void Notify()
        {
            foreach (Observer item in observerList)
            {
                item.Update();
            }
        }
    }
    public class Cat : Subject
    {
        private string catstate;
        public string CatState
        {
            get { return catstate; }
            set { catstate = value; }
        }
    }

//Observer接口
    public interface Observer
    {
        void Update();
}

//具体的Observer
    public class Mouse : Observer
    {
        private Cat cat;

        public Mouse(Cat cat)
        {
            this.cat = cat;
        }
        public void Update()
        {
            if (this.cat.CatState == "cry")
            {
                Console.WriteLine("The cat cry, and the Mouse run!" );
            }
        }
    }
    public class Human : Observer
    {
        private Cat cat;

        public Human(Cat cat)
        {
            this.cat = cat;
        }
        public void Update()
        {
            if (this.cat.CatState == "cry")
            {
                Console.WriteLine("The cat cry, and the Human wake!");
            }
        }
}

//系统开始运行
    class Program
    {
        static void Main(string[] args)
        {
            Cat cat = new Cat();
            cat.Attach(new Mouse(cat));
            cat.Attach(new Human(cat));

            cat.CatState = "cry";
            cat.Notify();
        }
    }

 

posted on 2014-07-10 08:38  yvictoryr  阅读(1868)  评论(11编辑  收藏  举报

导航