Skip to content

Instantly share code, notes, and snippets.

@charlag
Last active October 1, 2016 15:26
Show Gist options
  • Save charlag/1c4d52c76cdfc2c93352fd3504cddc04 to your computer and use it in GitHub Desktop.
Save charlag/1c4d52c76cdfc2c93352fd3504cddc04 to your computer and use it in GitHub Desktop.
Dependency injection prototyping
protocol CatalogViewModelFactory {
func create(parameters: String) -> CatalogViewModel
}
struct CatalogViewModelFactoryImpl: CatalogViewModelFactory {
func create(parameters: String) -> CatalogViewModel {
return CatalogViewModelImpl(something: parameters,
productFactory: ProductViewModelFactoryImpl()) // should be resolved for this factory
}
}
protocol CatalogViewModel {
var items: [String] { get }
var vmToOpenCatalog: CatalogViewModel { get }
func openProduct(index: Int) -> ProductViewModel
}
struct CatalogViewModelImpl: CatalogViewModel {
let productFactory: ProductViewModelFactory
let vmToOpenCatalog: CatalogViewModel
func openProduct(index: Int) -> ProductViewModel {
return productFactory.create(name: items[index])
}
let items: [String]
init(something: String, productFactory: ProductViewModelFactory) {
self.productFactory = productFactory
vmToOpenCatalog = CatalogViewModelImpl(something: "\(something) stupid",
productFactory: productFactory)
items = [something, "Cookie"]
}
}
protocol ProductViewModelFactory {
func create(name: String) -> ProductViewModel
}
struct ProductViewModelFactoryImpl: ProductViewModelFactory {
func create(name: String) -> ProductViewModel {
return ProductViewModelImpl(name: name)
}
}
protocol ProductViewModel {
var name: String { get }
var productToOpen: ProductViewModel { get }
}
struct ProductViewModelImpl: ProductViewModel {
let name: String
let productToOpen: ProductViewModel
init(name: String) {
self.name = name
productToOpen = ProductViewModelImpl(name: name)
}
}
protocol View { }
struct ProductView: View {
let viewModel: ProductViewModel
}
struct CatalogView: View {
let viewModel: CatalogViewModel
func openProduct() {
let vm = viewModel.openProduct(index: 0)
let productView = ProductView(viewModel: vm)
navigateTo(view: productView)
}
func navigateTo(view: View) {
print("Navigated to \(view)")
}
}
// ========
// these two are resolved
let catalogVMFactory = CatalogViewModelFactoryImpl()
let catalogVM = catalogVMFactory.create(parameters: "Hey")
let catalogView = CatalogView(viewModel: catalogVM)
catalogView.openProduct()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment