簡體   English   中英

目標C-單例靜態方法覆蓋不適用於多個子類

[英]Objective C - Singleton static method overriding doesn't work for multiple subclasses

我所擁有的

我的項目中有多個單例,它們共享一些范圍,字段和功能。 因此,我決定對它們進行結構化並創建一個稱為BaseSingleton的父類。 作為一個單例,它具有+(instancetype) sharedInstance ,因此其所有子類也將具有。 現在,我有一個BaseSingleton類和三個子類:

  • 公開Api
  • 用戶服務
  • 訂單存儲

+(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返回的實例PublicApiUserService返回UserServiceOrderStorage返回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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM