Observer观察者模式

来源:互联网 发布:北京方正网络客服电话 编辑:程序博客网 时间:2024/04/28 23:46

Observer观察者模式

     Observer设计模式是为了定义对象间的一对多的依赖关系,以便于当一个对象的状态改变时,其他依赖于它的对象会被自动告知并更新. Observer设计模式是一种松耦合的设计模式.


 namespace TestObserver    {        //观察者模式: Observer设计模式是为了定义对象间的一对多的依赖关系,以便于当一个对象的状态改变时,其他依赖于它的对象会被自动告知并更新.         //一下例子是当烧水器中的水温超过95度是,警报器和显示器都会提示水温,        //热水器        public class Heater        {            private int temperature;            public delegate void BolidHandler(int temp);//声明委托            public event BolidHandler BolidEvent;//声明事件            //烧水            public void BolidWater()            {                for (int i = 0; i <= 100; i++)                {                    temperature = i;                    if (temperature > 95)                    {                        if (BolidEvent != null)                            BolidEvent(temperature);                    }                }            }        }        //警报器        public class Alarm        {            public void MakeAlert(int tem)            {                Console.WriteLine("Alert,嘀嘀嘀,水温已经{0}度了.", tem);            }        }        //显示器        public class Display        {            public static void ShowMeg(int tem)            {                Console.WriteLine("Display,水快烧开了,水温已经{0}度了.", tem);            }        }        public class TestResult        {            public static void Run()            {                Heater heater = new Heater();                Alarm alarm = new Alarm();                heater.BolidEvent += alarm.MakeAlert;//注册警报器                heater.BolidEvent += Display.ShowMeg;//注册显示器                heater.BolidWater();//烧水,会自动调用注册过的对象的方法.            }        }    }