Observer Pattern (2)

设计模式原则:

努力使模块间为松散耦合

观察者模式:

建立对象之间一种一对多的依赖关系,使得一个对象的属性改变,其它依赖对象能够自动被通知以及更新。

Observer Pattern

示例代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using System.Security.Cryptography;

 

namespace Hello

{

   //interface

   interface Subject

   {

      void RegisterObserver(Observer user);

      void RemoveObserver(Observer user);

      void NotifyObserver();

   }

   interface Observer

   {

      void Update();

   }

   interface Display

   {

      void Show();

   }

 

   //Postal

   class Postal : Subject

   {

      List<Observer> ObserversList;

      public Postal()

      {

        ObserversList = new List<Observer>();

      }

      public void RegisterObserver(Observer user)

      {

        ObserversList.Add(user);

      }

      public void RemoveObserver(Observer user)

      {

        ObserversList.Remove(user);

      }

      public void NotifyObserver()

      {

        foreach (Observer user in ObserversList)

        {

           user.Update();

        }

      }

   }

 

   //user

   class User : Observer, Display

   {

      string userName;

      Subject postal;

      public User(string name, Subject subject)

      {

        userName = name;

        postal = subject;

      }

      public void Update()

      {

        Console.WriteLine("{0} receive the message.", userName);

      }

      public void Show()

      {

        Console.WriteLine("I'm user {0}", userName);

      }

      public void Register()

      {

        postal.RegisterObserver(this);

      }

      public void Remove()

      {

        postal.RemoveObserver(this);

      }

   }

   //

   class Program

   {

      static void Main(string[] args)

      {

        Postal postal = new Postal();

        User Mike = new User("Mike", postal);

        User Eric = new User("Eric", postal);

        User Erebus = new User("Erebus", postal);

 

        Mike.Register();

        Eric.Register();

        postal.NotifyObserver();

        Console.WriteLine();

        Mike.Remove();

        Erebus.Register();

        postal.NotifyObserver();

      }

   }

}

posted @ 2011-09-19 18:44  Erebus_NET  阅读(104)  评论(0编辑  收藏  举报