1

I have a parent and child class and an initializer in the child class that accepts some parameters and then calls super.init() to initialize the properties from the base class.

As I have a lot of child classes I want to reuse code for injecting the parameters but I can't figure out a way of injecting some of the members in the base class definition and the rest of them in the child class definition.

I tried the following:

public dynamic func baseManager() -> AnyObject {
    return TyphoonDefinition.withClass(BaseManager.self) {
        (definition) in

        definition.useInitializer("initWithBaseParam1:baseParam2:") {
            (initializer) in

            initializer.injectParameterWith(self.baseParam1())
            initializer.injectParameterWith(self.baseParam2())
        }
    }
}

public dynamic func authenticationManager() -> AnyObject {

    return TyphoonDefinition.withClass(AuthenticationManager.self) {
        (definition) in

        definition.parent = self.baseManager()
        definition.useInitializer("initWithChildParam1:childParam2:baseParam1:baseParam2:") {
            (initializer) in

            initializer.injectParameterWith(self.childParam1())
            initializer.injectParameterWith(self.childParam2())
        }
    }
}

But I get an error that I use an initializer with 4 parameters but only inject 2 of them. Is there a way I can make this work or do I have to refactor the base params to be properties like the example in the docs?

4

1 回答 1

1

您可以从父级继承初始化程序或覆盖它,但不幸的是,除了父模板中定义的参数之外,您不能使用额外参数扩展初始化程序。

建议的替代品:

使用属性注入

通常,我们建议支持初始化注入,它允许创建不可变对象并在构造后进行状态验证。属性注入中的这些缺点可以通过以下方式解决:

  • 指定注入属性后要使用的回调方法。
  • 对于设计为不可变的实例,将属性声明为内部读写,但外部只读。

使用组合而不是继承

另一个建议是创建一个适当范围的定义,封装倾向于一起使用的配置并将其注入。

根据具体情况,这可能是有利的——有很多关于“组合与继承”的好文章以及何时适合。

于 2015-07-14T12:04:33.437 回答