1

让这个类从不直接使用,只继承:

class ApiBase {}

我如何default在这里定义一个通用的静态单例?- 所以我可以:

class FooApi: ApiBase {}  // Want only one instance of `FooApi`
class BarApi: ApiBase {}  // Want only one instance of `BarApi`

FooApi.default.foo_api_only_method_name()
BarApi.default.bar_api_only_method_name()

我唯一能想到的就是创建一个protocol需要实现FooApi的内容。BarApi但这似乎不是最理想的,宁愿写一个像这样的实现:

func `default`<T: ApiBase>() -> T {
    if staticInstance == nil {
        staticInstance = T()
    }
    return staticInstance
}
4

2 回答 2

1

我无法找到使用泛型解决此问题的方法,但我的建议是

static let `default` = FooApi()

static let `default` = BarApi()

分为两个子类。这样,每个人都可以创建自己的单例,而无需太多额外的代码。

于 2018-02-25T15:31:04.980 回答
1

最后添加一个接口:

protocol Instance {
    associatedtype T
    // static var _instance: T {get set}  # Can't use; can't override :(
    static func instance() -> T
}

可以这样使用:

class ApiBase: Instance {
    var root: String = ""

    static var _instance: ApiBase = ApiBase()

    open class func instance() -> ApiBase {
        if _instance.root == "" {
            _instance = ApiBase()
        }
        return _instance
    }
}

遗产:

class FooApi: ApiBase {
    static var _fooApi: FooApi = FooApi()

    override class func instance() -> FooApi {
        if _fooApi.root == "" {
            _fooApi = FooApi()
        }
        return _instance
    }
}

这是次优的,因为主体的instance功能在模式上是相同的。但它有效。

于 2018-03-04T01:01:42.720 回答