這個或許叫源-***(source/listener)模式更加形象。
觀察者模式定義了一種一對多的依賴關係,讓多個觀察者物件同時監聽某乙個主題物件。這個主題物件在狀態上發生變化時,會通知所有觀察者物件,使它們能夠自動更新自己。
the classes and/or objects participating in this pattern are:
concretesubject(ibm)
observer(iinvestor)
concreteobserver(investor)
// observer pattern -- real world example
using system;
using system.collections.generic;
namespace dofactory.gangoffour.observer.realworld
///
//////
observer design pattern.
///class
//////
///static
void main()
// create ibm stock and attach investors
ibm ibm = new
ibm("ibm", 120.00);
ibm.attach(new
investor("sorros"));
ibm.attach(new
investor("berkshire"));
// fluctuating prices will notify investors
ibm.price = 120.10;
ibm.price = 121.00;
ibm.price = 120.50;
ibm.price = 120.75;
// wait for user
console.readkey();
///
///the 'subject' abstract class
///abstract
class
stock
private
string _symbol;
private
double _price;
private
list
_investors = new
list
();// constructor
public stock(string symbol, double price)
this._symbol = symbol;
this._price = price;
public
void attach(iinvestor investor)
_investors.add(investor);
public
void detach(iinvestor investor)
_investors.remove(investor);
public
void notify()
foreach (iinvestor investor in _investors)
investor.update(this);
console.writeline("");
// gets or sets the price
public
double price
get
set
if (_price != value)
_price = value;
notify();
// gets the symbol
public
string symbol
get
///
///the 'concretesubject' class
///class
ibm : stock
// constructor
public ibm(string symbol, double price)
: base(symbol, price)
///
///the 'observer' inte***ce
///inte***ce
iinvestor
void update(stock stock);
///
///the 'concreteobserver' class
///class
investor : iinvestor
private
string _name;
private
stock _stock;
// constructor
public investor(string name)
this._name = name;
public
void update(stock stock)
console.writeline("notified of 's " +
"change to ", _name, stock.symbol, stock.price);
// gets or sets the stock
public
stock stock
get
set
output
notified sorros of ibm's change to $120.10
notified berkshire of ibm's change to $120.10
notified sorros of ibm's change to $121.00
notified berkshire of ibm's change to $121.00
notified sorros of ibm's change to $120.50
notified berkshire of ibm's change to $120.50
notified sorros of ibm's change to $120.75
notified berkshire of ibm's change to $120.75
觀察者模式 Observer
個人理解 觀察者模式的核心是subject的attach和detach方法,載入observer物件 uml類圖 實現 public abstract class subject public void detach observer observer public void notify publ...
觀察者模式 ObServer
觀察者模式 observer 定義物件間的一種一對多的依賴關係,當乙個物件的狀態發生改變時,所有依賴於它的物件都得到通知並被自動更新 觀察者模式 observer 觀察者模式定義了一對多依賴關係,讓多個觀察者物件同時監聽某乙個主題物件。讓主題物件在狀態發生變化時,會通知所有觀察者物件,讓他們能夠自動...
觀察者模式(OBSERVER)
觀察者模式是我選擇將其列出來的第乙個模式。看了這個模式的概念之後,有種豁然開朗的感覺。工作也由實踐上公升到了理論。平時使用的各種 net 控制項都使用了這種模式,將這種模式應用到組成乙個系統的各個元件中去,怎乙個 妙 字了得。理解了它之後,不竟又對 net 的框架敬佩有佳。不知道這其中隱藏了多少未知...