[英]Inject delegate method from derived to base class using constructor
今天,我正在重構一個庫,該庫可以在多個平台(WPF,WF,WP7,WP8)上創建和共享代碼。
這個想法是我使用繼承來擴展類中的功能。 頂級類向客戶端公開了幾個事件,此事件在方法中引發,該方法使用接受某些參數的構造函數傳遞給基類。
該對象基本上用作單例。
例:
public class SomeHandler : BaseHandler
{
public event EventHandler<Custom1EventArgs> RequestCompleted = delegate {};
public event EventHandler<Custom2EventArgs> ActionHandled = delegate { };
protected SomeHandler()
: base(new CustomUtil(), new CustomRepository(),
new AnotherRepository(ADelegateMethod),
AnotherDelegateMethod, AnotherOneDelegateMethod) {}
#region [ Singleton ]
public static SomeHandler Instance
{ get { return Nested.instance;} }
class Nested
{
internal static readonly SomeHandler instance = new SomeHandler ();
}
#endregion
private static void ADelegateMethod(Custom1EventArgs args)
{
Instance.RequestCompleted (Instance, args);
}
private static void AnotherDelegateMethod(
Custom2EventArgs args, CustomObject result)
{
// Do stuff....
AnotherCustomObject cusObj = new AnotherCustomObject(args);
Instance.ActionHandled (Instance, cusObj);
}
private static void AnotherOneDelegateMethod(CustomObject result)
{
// Do some stuff...
}
}
好的,如果您已經注意到,我需要將委托方法標記為靜態,因為在構造函數參數中發生了注入。 但這迫使我將事件靜態化。 要解決此問題,我依賴於這樣的事實,即用戶始終使用我的對象的Instance
singleton實例,盡管可以根據需要初始化該對象,但目前還不能選擇sealed
,因為它還用作另一個對象的基繼承類。類在特定的特殊實現中。
將事件更改為靜態是否不好? 對我來說似乎不合適,您怎么看? 這種設計可以改善嗎?
實際上,我將委托用作需要在特定時間內從其他對象new AnotherRepository(ADelegateMethod)
或BaseHandler
類執行的代碼的一部分,因此我基本上可以為客戶端提供信息。
我建議更改的主要內容是:
AnotherDelegateMethod
和AnotherOneDelegateMethod
(然后從父類調用)。 至於另一件事,這完全取決於您的類要實現的邏輯。 可能需要更多的去耦 。
新的AnotherRepository(ADelegateMethod)。 這確實是一個棘手的問題,如何正確地做所有事情-由於可能采用不同的方法 ,因此需要更多有關常規邏輯的信息:
protected virtual ISomeRepositoryInterface CreateRepositoryInstance()
(例如); 您可以使用依賴注入到一些外部類中,這些類將使用您的處理程序來傳遞存儲庫,實際上與工具或另一個存儲庫相同(但同樣,一切都取決於通用邏輯);
定制處理程序的一種方法是將基本類設置為Generic,並通過提供一些具體的類來繼承子級,該邏輯與繼承者完全相關,但大多數僅在父類中使用。
關於事件:
此外,至於@durilka的回答(但是,考慮到他的俄語昵稱“騙子”,相信他真的很有趣):他正確地提到了(在我進入之前):
擺脫嵌套。 聲明私有的默認構造函數。 在返回現有實例或創建新return instance ?? instance = new SomeHandler()
(又名return instance ?? instance = new SomeHandler()
),在您的Instance屬性中使用它。 並開始考慮從代表轉移到某種消息總線。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.