扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:Doug Purdy Jeffrey Richter 来源:程序员》杂志 2007年11月8日
关键字: Windows
//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 |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者