观察者示例(C#)
| //represents a stock in an application public class Stock:ObservableImpl { //instance variable for ask price object _askPrice; //property for ask price public object AskPrice { set { _askPrice=value; base.NotifyObservers(_askPrice); }//set }//AskPrice property }//Stock //represents the user interface in the application public class StockDisplay:IObserver { public void Notify(object anObject){ Console.WriteLine("The new ask price is:" + anObject); }//Notify }//StockDisplay public class MainClass{ public static void Main() { //create new display and stock instances StockDisplay stockDisplay=new StockDisplay(); Stock stock=new Stock(); //register the grid stock.Register(stockDisplay); //loop 100 times and modify the ask price for(int looper=0;looper < 100;looper++) { stock.AskPrice=looper; } //unregister the display stock.UnRegister(stockDisplay); }//Main }//MainClass |
| public class Stock { //declare a delegate for the event public delegate void AskPriceDelegate(object aPrice); //declare the event using the delegate public event AskPriceDelegate AskPriceChanged; //instance variable for ask price object _askPrice; //property for ask price public object AskPrice { set { //set the instance variable _askPrice=value; //fire the event AskPriceChanged(_askPrice); } }//AskPrice property }//Stock class //represents the user interface in the application public class StockDisplay { public void AskPriceChanged(object aPrice) { Console.Write("The new ask price is:" + aPrice + "/r/n"); } }//StockDispslay class public class MainClass { public static void Main(){ //create new display and stock instances StockDisplay stockDisplay=new StockDisplay(); Stock stock=new Stock(); //create a new delegate instance and bind it //to the observer's askpricechanged method Stock.AskPriceDelegate aDelegate=new Stock.AskPriceDelegate(stockDisplay.AskPriceChanged); //add the delegate to the event stock.AskPriceChanged+=aDelegate; //loop 100 times and modify the ask price for(int looper=0;looper < 100;looper++) { stock.AskPrice=looper; } //remove the delegate from the event stock.AskPriceChanged-=aDelegate; }//Main }//MainClass |
http://dev.xuezhishi.net/website/NET/2007-10-17/20797.html