名稱 | Observer |
結(jié)構(gòu) | |
意圖 | 定義對象間的一種一對多的依賴關(guān)系,當(dāng)一個對象的狀態(tài)發(fā)生改變時, 所有依賴于它的對象都得到通知并被自動更新。 |
適用性 | - 當(dāng)一個抽象模型有兩個方面, 其中一個方面依賴于另一方面。將這二者封裝在獨(dú)立的對象中以使它們可以各自獨(dú)立地改變和復(fù)用。
- 當(dāng)對一個對象的改變需要同時改變其它對象, 而不知道具體有多少對象有待改變。
- 當(dāng)一個對象必須通知其它對象,而它又不能假定其它對象是誰。換言之, 你不希望這些對象是緊密耦合的。
|
|
|

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;
}
}
}