Learning from Open Source Generic Factory

Issue #148

From https://github.com/devxoul/Pure/blob/master/Sources/Pure/FactoryModule.swift

1
2
3
4
5
6
7
8
public protocol FactoryModule: Module {

/// A factory for `Self`.
associatedtype Factory = Pure.Factory<Self>

/// Creates an instance of a module with a dependency and a payload.
init(dependency: Dependency, payload: Payload)
}

From https://github.com/devxoul/Pure/blob/master/Sources/Pure/Factory.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
open class Factory<Module: FactoryModule> {
private let dependencyClosure: () -> Module.Dependency

/// A static dependency of a module.
open var dependency: Module.Dependency {
return self.dependencyClosure()
}

/// Creates an instance of `Factory`.
///
/// - parameter dependency: A static dependency which should be resolved in a composition root.
public init(dependency: @autoclosure @escaping () -> Module.Dependency) {
self.dependencyClosure = dependency
}

/// Creates an instance of a module with a runtime parameter.
///
/// - parameter payload: A runtime parameter which is required to construct a module.
open func create(payload: Module.Payload) -> Module {
return Module.init(dependency: self.dependency, payload: payload)
}
}

From https://github.com/devxoul/Pure/blob/master/Tests/PureTests/PureSpec.swift#L72

1
2
3
4
5
6
let factory = FactoryFixture<Dependency, Payload>.Factory(dependency: .init(
networking: "Networking A"
))
let instance = factory.create(payload: .init(id: 100))
expect(instance.dependency.networking) == "Networking A"
expect(instance.payload.id) == 100

Comments