📄 observerrealworld.cs
字号:
using System;
using System.Windows.Forms;
using System.Collections;
//观察者模式(Observer pattern)
//意图
// 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。
//适用性
// 1.当一个抽象模型有两个方面, 其中一个方面依赖于另一方面。将这二者封装在独立的对象中以使它们可以各自独立地改变和复用。
// 2.当对一个对象的改变需要同时改变其它对象, 而不知道具体有多少对象有待改变。
// 3.当一个对象必须通知其它对象,而它又不能假定其它对象是谁。换言之, 你不希望这些对象是紧密耦合的。
//说明
// Subject 具有 Notify 方法,会依次通知每一个 Observer
//例子
// 使用 TestResult(对应于Subject)记录测试结果,然后将该信息传递给 TestListener(对应于Observer)的实现子类(如 TextTestProgressListener)输出测试结果
// TestResult 维护了一个指向 TestListener 对象的指针队列( std::deque<TestListener *> m_listeners; )
namespace DesignPattern.ObserverRealWorld
{
class ObserverRealWorld : AbstractPattern
{
public static void Run(TextBox tbInfo)
{
s_tbInfo = tbInfo;
s_tbInfo.Text = "";
// Create investors
Investor s = new Investor("Sorros");
Investor b = new Investor("Berkshire");
// Create IBM stock and attach investors
IBM ibm = new IBM("IBM", 120.00);
ibm.Attach(s);
ibm.Attach(b);
// Change price, which notifies investors
ibm.Price = 120.10;
ibm.Price = 121.00;
ibm.Price = 120.50;
ibm.Price = 120.75;
// Wait for user
//Console.Read();
}
}
// "Subject"
abstract class Stock
{
protected string symbol;
protected double price;
private ArrayList investors = new ArrayList();
// Constructor
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);
}
DesignPattern.FormMain.OutputInfo("");
}
// Properties
public double Price
{
get{ return price; }
set
{
price = value;
Notify();
}
}
public string Symbol
{
get{ return symbol; }
set
{
symbol = value;
}
}
}
// "ConcreteSubject"
class IBM : Stock
{
// Constructor
public IBM(string symbol, double price) : base(symbol, price)
{
}
}
// "Observer"
interface IInvestor
{
void Update(Stock stock);
}
// "ConcreteObserver"
class Investor : IInvestor
{
private string name;
private Stock stock;
// Constructor
public Investor(string name)
{
this.name = name;
}
public void Update(Stock stock)
{
DesignPattern.FormMain.OutputInfo("Notified {0} of {1}'s " + "change to {2:C}", name, stock.Symbol, stock.Price);
}
// Property
public Stock Stock
{
get{ return stock; }
set{ stock = value; }
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -