entArgs类的专门用法。
事件模式示例(C#)
public class Stock {
//declare a delegate for the event
public delegate void AskPriceChangedHandler(object sender,
AskPriceChangedEventArgs e);
//declare the event using the delegate
public event AskPriceChangedHandler 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
OnAskPriceChanged();
}
}//AskPrice property
//method to fire event delegate with proper name
protected void OnAskPriceChanged() {
AskPriceChanged(this,new AskPriceChangedEventArgs(_askPrice));
}//AskPriceChanged
}//Stock class
//specialized event class for the askpricechanged event
public class AskPriceChangedEventArgs:EventArgs {
//instance variable to store the ask price
private object _askPrice;
//constructor that sets askprice
public AskPriceChangedEventArgs(object askPrice) { _askPrice=askPrice; }
//public property for the ask price
public object AskPrice { get { return _askPrice; } }
}//AskPriceChangedEventArgs
结论
基于这里对Observer模式的分析,我们可以清楚地看到此模式提供了一个完美的机制,能够在应用程序中的对象之间划定清晰的界限。虽然通过回调进行实现(使用IObserver和IObservable接口)相当简单,但CLR的委托和事件概念可处理大多数“繁重的工作”,并降低主体和观察者之间的耦合级别。实际上,通过正确地使用此模式,在确保应用程序可演变性方面就会向前迈出一大步。当您的UI和业务要求随时间发生变化时,Observer模式可确保能够简化您的工作。
在开发灵活的应用程序方面,设计模式是一个非常强大的工具(如果有效地加以运用)。撰写本文是为了说明模式方法的有效性,并重点说明.NET框架中使用的一种模式。将来的文章将继续探究FCL中的模式,并简要介绍一些用于生成有效Web服务的模式。
事件模式示例(C#)
public class Stock {
//declare a delegate for the event
public delegate void AskPriceChangedHandler(object sender,
AskPriceChangedEventArgs e);
//declare the event using the delegate
public event AskPriceChangedHandler 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
OnAskPriceChanged();
}
}//AskPrice property
//method to fire event delegate with proper name
protected void OnAskPriceChanged() {
AskPriceChanged(this,new AskPriceChangedEventArgs(_askPrice));
}//AskPriceChanged
}//Stock class
//specialized event class for the askpricechanged event
public class AskPriceChangedEventArgs:EventArgs {
//instance variable to store the ask price
private object _askPrice;
//constructor that sets askprice
public AskPriceChangedEventArgs(object askPrice) { _askPrice=askPrice; }
//public property for the ask price
public object AskPrice { get { return _askPrice; } }
}//AskPriceChangedEventArgs
结论
基于这里对Observer模式的分析,我们可以清楚地看到此模式提供了一个完美的机制,能够在应用程序中的对象之间划定清晰的界限。虽然通过回调进行实现(使用IObserver和IObservable接口)相当简单,但CLR的委托和事件概念可处理大多数“繁重的工作”,并降低主体和观察者之间的耦合级别。实际上,通过正确地使用此模式,在确保应用程序可演变性方面就会向前迈出一大步。当您的UI和业务要求随时间发生变化时,Observer模式可确保能够简化您的工作。
在开发灵活的应用程序方面,设计模式是一个非常强大的工具(如果有效地加以运用)。撰写本文是为了说明模式方法的有效性,并重点说明.NET框架中使用的一种模式。将来的文章将继续探究FCL中的模式,并简要介绍一些用于生成有效Web服务的模式。
| 对此文章发表了评论 |

