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