[英]Objective C - Singleton static method overriding doesn't work for multiple subclasses
我所擁有的 :
我的項目中有多個單例,它們共享一些范圍,字段和功能。 因此,我決定對它們進行結構化並創建一個稱為BaseSingleton的父類。 作為一個單例,它具有+(instancetype) sharedInstance
,因此其所有子類也將具有。 現在,我有一個BaseSingleton
類和三個子類:
+(instancetype) sharedInstance
中的+(instancetype) sharedInstance
具有一個常見的實現:
+(instancetype) sharedInstance {
static BaseSingleton* _sharedInstance = nil;
static dispatch_once_t once_token;
dispatch_once(&once_token, ^{
_sharedInstance = [[self alloc] init]; // no override for init method
});
return _sharedInstance;
}
我需要的:
在對它們調用sharedInstance
時,我需要我的Singleton子類才能正常工作。 含義, PublicApi
返回的實例PublicApi
, UserService
返回UserService
和OrderStorage
返回OrderStorage
情況下, 沒有必要實施sharedInstance。
問題是什么 :
所以我認為在+(instancetype) sharedInstance
中利用instancetype
可以完成這項工作,因為使用instancetype
使類方法返回相關的返回類型 (請參閱NSHipster文章 )。 因此,如果在PublicApi或UserService上調用, sharedInstance
將返回相關類型,分別是PublicApi或UserService(同樣,兩者均未實現sharedInstance
)。
這僅適用於一個子類( PublicApi
)。 但是,當添加其他兩個子類時,在其中某些子類上調用sharedInstance
並不會完全導致正確的返回類型。 因此,例如, [PublicApi sharedInstance]
將返回的實例PublicApi
,但[UserService sharedInstance]
也將返回的實例PublicApi
,對於同樣的事情OrderStorage
。
我認為問題_sharedInstance
在[BaseSingleton sharedInstance]
實現中的靜態_sharedInstance
。 [PublicApi sharedInstance]
在應用程序運行時首先被調用,因此dispatch_once
方法實例化_sharedInstance
並將其賦予PublicApi
類型。 dispatch_once
內部的代碼塊不再執行,這就是為什么該靜態變量從不更改其類型,並在[UserService sharedInstance]
和[OrderStorage sharedInstance]
[UserService sharedInstance]
其作為PublicApi
返回的[OrderStorage sharedInstance]
。
有什么優雅的方法可以解決我的問題嗎? (當然,除了為每個子類實現sharedInstance
之外,還sharedInstance
實現從BaseSingleton繼承的全部目的)。
單身人士的共同基類本身就是矛盾。
應該顯而易見的是,對於您的sharedSingleton實現,只有一個 dispatch_once_t令牌。 因此,dispatch_once_t中的代碼將僅在您的應用程序中執行一次 。 _sharedInstance只有一個靜態變量,因此它不可能返回兩個不同的sharedInstance值。
不要這樣
如前所述,該體系結構存在問題,這很可能。 在sharedInstance中,您需要一組級聯的測試來確定'self'(類)是否==說[Public class] else ...
這樣,您的方法將有多個靜態變量,每個處理的類一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.