Observer设计模式

假设热水器由三部分组成,热水器,警报器,显示器,它们来自于不同厂商进行组装,那么,热水器应该仅负责烧水,不能发出警报和显示水温;

//热水器
    public class Heater {
        public delegate void BoilHandler(int param);
        public event BoilHandler BoilEvent;
        //水温
        private int temperature;
        //烧水
        public void BoilWater() {
            for (int i = 0; i <= 100; i++) {
                temperature = i;

                if (temperature > 95) {
                    BoilEvent(temperature);
                }
            }
        }
    }

  

 //警报器
    public class Alarm {
        //发出警报
        public static void MakeAlert(int param) {
            Console.WriteLine("Alarm:水已经{0}度了",param);
        }
    }

  

 //显示器
    public class Display {
        //显示温度
        public static void ShowMsg(int param)
        {
            Console.WriteLine("Display:水快烧开,当前温度:{0}度",param);
        }
    }

  

 
 class Program
    {
        static void Main(string[] args)
        {

            Heater heater = new Heater();
            heater.BoilEvent += Alarm.MakeAlert;
            heater.BoilEvent += Display.ShowMsg;
            heater.BoilWater();
        }
    }

 

posted @ 2014-12-25 11:15  10:00  阅读(133)  评论(0)    收藏  举报