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

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