4.7 Observer(观察者)

【返回目录】

我们常常听说“联合国军事观察员”这个名词,那么军事观察员到底是做什么的呢?

太多细节其实我们这些当老百姓的没有必要也不可能知道,我们只需要知道,军事观察员就是联合国派驻到某些政局比较动荡、到处战乱纷扰的危险地带起到对局势进行观察和上报作用的联合国军事工作人员。比如,乌干达证据不太稳定,随时可能爆发内战,进而可能升级导致种族大屠杀,这是人类社会不愿看到的悲剧。于是联合国派遣由中美两名军事观察员组成的观察团进驻乌干达,一旦局势发生变化就立即向上级部门报告。这也就是观察者模式。

   1: using System;
   2: using System.Collections;
   3:  
   4: namespace Autumoon.DesignPatterns.Observer
   5: {
   6:     public class Country
   7:     {
   8:         public string Name { get; set; }
   9:         public string Status { get; set; }
  10:         private ArrayList _observers = null;
  11:  
  12:         public Country()
  13:         {
  14:             this.Status = "No War.";
  15:             this._observers = new ArrayList();
  16:         }
  17:  
  18:         public void Attach(ObserverDemo observer)
  19:         {
  20:             this._observers.Add(observer);
  21:             observer.ObservedCountry = this;
  22:         }
  23:  
  24:         public void Detach(ObserverDemo observer)
  25:         {
  26:         }
  27:  
  28:         public void Notify()
  29:         {
  30:             foreach (ObserverDemo observer in this._observers)
  31:             {
  32:                 observer.Update();
  33:             }
  34:         }
  35:     }
  36:  
  37:     public class ConcreteCountry : Country
  38:     {
  39:         public string State { get; set; }
  40:     }
  41:  
  42:     abstract public class ObserverDemo
  43:     {
  44:         public Country ObservedCountry { get; set; }
  45:  
  46:         abstract public void Update();
  47:     }
  48:  
  49:     public class ConcreteObserver : ObserverDemo
  50:     {
  51:         public string Name { get; set; }
  52:  
  53:         public ConcreteObserver(string name)
  54:         {
  55:             this.Name = name;
  56:         }
  57:  
  58:         override public void Update()
  59:         {
  60:             Console.WriteLine(this.Name + ": " + this.ObservedCountry.Status);
  61:         }
  62:     }
  63: }

如果乌干达没发生什么事情倒也罢,一旦有任何情况,观察员都必须跟上级部门报告,而不是坐山观虎斗。

   1: static void Main(string[] args)
   2: {
   3:     #region Observer
   4:     ConcreteCountry country = new ConcreteCountry();
   5:     country.Name = "Uganda";
   6:  
   7:     ConcreteObserver chineseObserver = new ConcreteObserver("Chinese observer");
   8:     ConcreteObserver americanObserver = new ConcreteObserver("American observer");
   9:  
  10:     country.Attach(chineseObserver);
  11:     country.Attach(americanObserver);
  12:  
  13:     country.Status = "There's no war.";
  14:     country.Notify();
  15:  
  16:     country.Status = "There's some sound of gun in somewhere.";
  17:     #endregion
  18:  
  19:     Console.ReadLine();
  20: }

Heal The World

posted @ 2008-02-23 12:04  麦机长  阅读(937)  评论(0编辑  收藏  举报