Skip to content

Instantly share code, notes, and snippets.

@codecat15
Created September 9, 2023 22:51
Show Gist options
  • Save codecat15/4cf2f14e6616f9afaca5eabcf34606fc to your computer and use it in GitHub Desktop.
Save codecat15/4cf2f14e6616f9afaca5eabcf34606fc to your computer and use it in GitHub Desktop.
Builder Pattern for creating instance of ViewModel with Dependency Injection
// Dependency Inversion Principle: Define protocols for Service and Repository
protocol Service {
func fetchData() -> String
}
protocol Repository {
func saveData(data: String)
}
// Concrete implementations of Service and Repository
class ConcreteService: Service {
func fetchData() -> String {
return "Data from Service"
}
}
class ConcreteRepository: Repository {
func saveData(data: String) {
print("Saving data: \(data)")
}
}
// ViewModel with dependencies
class ViewModel {
private let service: Service
private let repository: Repository
init(service: Service, repository: Repository) {
self.service = service
self.repository = repository
}
func processData() {
let data = service.fetchData()
repository.saveData(data: data)
}
}
// Builder for ViewModel
class ViewModelBuilder {
private var service: Service?
private var repository: Repository?
func setService(_ service: Service) -> ViewModelBuilder {
self.service = service
return self
}
func setRepository(_ repository: Repository) -> ViewModelBuilder {
self.repository = repository
return self
}
func build() -> ViewModel {
guard let service = service, let repository = repository else {
fatalError("Service and Repository must be set before building ViewModel.")
}
return ViewModel(service: service, repository: repository)
}
}
// Usage
let viewModel = ViewModelBuilder()
.setService(ConcreteService())
.setRepository(ConcreteRepository())
.build()
viewModel.processData()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment