public void BoilWater()//烧水 { for (int i = 0; i <= 99; i++) { temprature = i + 1; if (temprature > 97)//当水快烧开时(温度>97度),通知Observer { BoiledEventArgs e = new BoiledEventArgs(temprature, type, area); OnBoiled(e); } } }
private bool isDisplayedType = false;//标记变量,标示是否已经打印过 public void Update(BoiledEventArgs e) { if (!isDisplayedType) { Console.WriteLine("{0}-{1}:", e.Area, e.Type); Console.WriteLine(); isDisplayedType = true; } if (e.Temperature < 100) { Console.WriteLine(string.Format("Alarm".PadRight(7) + ":水快烧开了,当前温度:{0}。", e.Temperature)); } else { Console.WriteLine(string.Format("Alarm".PadRight(7) + ":水已经烧开了!!")); } }
//供子类覆盖,以便子类拒绝被通知,或添加额外行为 protected virtual void OnBoiled(BoiledEventArgs e) { base.Notify(e);//调用父类Notify方法,进而调用所有祖册了Observer的Update方法 }