Life is Good.

Enhance Tech and English
随笔 - 65, 文章 - 20, 评论 - 21, 引用 - 0
数据加载中……

Observer

名称 Observer
结构

意图 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。
适用性
  • 当一个抽象模型有两个方面, 其中一个方面依赖于另一方面。将这二者封装在独立的对象中以使它们可以各自独立地改变和复用。
  • 当对一个对象的改变需要同时改变其它对象, 而不知道具体有多少对象有待改变。
  • 当一个对象必须通知其它对象,而它又不能假定其它对象是谁。换言之, 你不希望这些对象是紧密耦合的。



namespace Observer
{
  
public abstract class Stock // Subject
  {
    
protected string name;
    
protected double price;
    
private ArrayList inventors = new ArrayList();

    
public Stock(string name, double price)
    {
      
this.name = name;
      
this.price = price;
    }

    
public void Attach(Investor investor)
    {
      inventors.Add(investor);
    }

    
public void Detach(Investor investor)
    {
      inventors.Remove(investor);
    }

    
public void Notify()
    {
      
foreach (Investor investor in inventors)
      {
        investor.Update(
this);
      }
    }

    
// Properties 
    public double Price
    {
      
get { return price; }
      
set
      {
        price 
= value;
        Notify();
      }
    }

    
public Investor Investor
    {
      
get
      {
        
throw new System.NotImplementedException();
      }
      
set
      {
      }
    }
  }

  
public class ADSK : Stock
  {
    
public ADSK(string name, double price)
      :
base(name, price)
    {

    }

  }

  
public class ABB : Stock
  {
     
public ABB(string name, double price)
      :
base(name, price)
    {

    }
  }
}


namespace Observer
{
  
public abstract class Investor // Observer
  {
    
abstract public void Update(Stock stock);
  }

  
public class SmallInvestor : Investor
  {
    
private string name;
    
public SmallInvestor(string name)
    {
      
this.name = name;
    }

    
override public void Update(Stock stock)
    {
      Console.WriteLine(
"Small Investor is Notified! ");
    }
  }

  
public class BigInvestor : Investor
  {
   
private string name;
    
public BigInvestor(string name)
    {
      
this.name = name;
    }
    
override  public void Update(Stock stock)
    {
      Console.WriteLine(
"Big Investor is Notified! ");
    }
  }
}


namespace Observer
{
  
class Program
  {
    
static void Main(string[] args)
    {
      
// Create investors/ Observers
      SmallInvestor s = new SmallInvestor("Small Investor");
      BigInvestor b 
= new BigInvestor("Big Investor");

      ADSK adsk 
= new ADSK("ADSK"46.0);
      ABB abb 
= new ABB("ABB"23.4);

      adsk.Attach(s);
      adsk.Attach(b);

      abb.Attach(s);
      abb.Attach(b);

      adsk.Price 
= 48;
      abb.Price 
= 26;

      
return;
    }
  }
}

posted on 2011-06-11 22:32 Mike Song 阅读(223) 评论(0)  编辑 收藏 引用 所属分类: Design Pattern


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理