Created
June 28, 2016 06:02
-
-
Save ukitaka/cefbfcb523b10150dec1eeb3e0dc1ccc to your computer and use it in GitHub Desktop.
Lightweight DI Framework Cleanse memo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. インターフェースをつくる | |
protocol UserRepository { | |
func findByID(userID: UserID) -> User | |
} | |
// 2. 実装を作る | |
class UserDAO: UserRepository { | |
init() { ... } | |
func findByID(userID: UserID) -> User { | |
... | |
} | |
} | |
// 3. Moduleを作る | |
// - 依存として注入されるオブジェクト | |
// - つまりDependency | |
struct UserRepositoryModule: Module { | |
func configure<B : Binder>(binder binder: B) { | |
// UserRepositoryの実装としてUserDAOを使うよという意味 | |
binder.bind(UserRepository.self).asSingleton().to(factory: UserDAO.init) | |
} | |
} | |
// 4. 注入先のオブジェクトをつくる | |
class UserListUseCase { | |
let userRepository: UserRepository | |
init(userRepository: UserRepository) { | |
self.userRepository = userRepository | |
} | |
} | |
// 5. Component作成 | |
struct UserListUseCaseComponent: Component { | |
typealias Root = UserListUseCase | |
func configure<B : Binder>(binder binder: B) { | |
binder.install(module: UserRepositoryModule()) | |
// Bind our root object | |
binder.bind().to(factory: UserListUseCase.init) | |
} | |
} | |
// 6. オブジェクト生成 | |
let useCase: UserListUseCase = try! UserListUseCaseComponent().build() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment