泡泡

              宠辱不惊-闲看庭前花开花落
                           去留无意-漫观天外云展云舒
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

19)Observer

Posted on 2007-09-21 15:42  AlanPaoPao  阅读(125)  评论(0)    收藏  举报
    观察者模式的目的是: 当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新
    实例代码:
interface IInvestor
{
  
void Update(Stock stock);
}

abstract class Stock
{
  
protected string symbol;
  
protected double price;
  
private ArrayList investors = new ArrayList();
  
public Stock(string symbol, double price)
  
{
    
this.symbol = symbol;
    
this.price = price;
  }

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

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

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

    Console.WriteLine(
"");
  }

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

  }

  
public string Symbol
  
{
    
get return symbol; }
    
set { symbol = value; }
  }

}

class IBM : Stock
{
  
public IBM(string symbol, double price)
    : 
base(symbol, price)
  
{
  }

}

class Investor : IInvestor
{
  
private string name;
  
private Stock stock;
  
public Investor(string name)
  
{
    
this.name = name;
  }

  
public void Update(Stock stock)
  
{
    Console.WriteLine(
"Notified {0} of {1}'s " + "change to {2:C}", name, stock.Symbol, stock.Price);
  }

  
public Stock Stock
  
{
    
get return stock; }
    
set { stock = value; }
  }

}

class MainApp
{
  
static void Main()
  
{
    Investor s 
= new Investor("Sorros");
    Investor b 
= new Investor("Berkshire");
    IBM ibm 
= new IBM("IBM"120.00);
    ibm.Attach(s);
    ibm.Attach(b);
    ibm.Price 
= 120.10;
    ibm.Price 
= 121.00;
    ibm.Price 
= 120.50;
    ibm.Price 
= 120.75;
    Console.Read();
  }

}