Created
September 9, 2023 22:48
-
-
Save codecat15/ab7d16605ad01de1d8c403f422357905 to your computer and use it in GitHub Desktop.
Swift Factory Design Pattern with Dependency Inversion Principle
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
// 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) | |
} | |
} | |
// Factory for creating ViewModel instances | |
class ViewModelFactory { | |
static func createViewModel() -> ViewModel { | |
let service = ConcreteService() | |
let repository = ConcreteRepository() | |
return ViewModel(service: service, repository: repository) | |
} | |
} | |
// Usage | |
let viewModel = ViewModelFactory.createViewModel() | |
viewModel.processData() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment