Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Learning from Open Source: Generic Factory #148

Open
onmyway133 opened this issue Jan 26, 2018 · 0 comments
Open

Learning from Open Source: Generic Factory #148

onmyway133 opened this issue Jan 26, 2018 · 0 comments

Comments

@onmyway133
Copy link
Owner

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

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

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

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant