ArchitectureMidMCQ
What is the Factory pattern?
Test your knowledge:
Explanation & Code
Answer: The Factory pattern creates objects without exposing the creation logic. The caller asks for an object and gets one back — without knowing which concrete type was created.
Code Example:
// Simple factory function
enum Environment { case dev, staging, production }
struct NetworkClientFactory {
static func make(for environment: Environment) -> NetworkClientProtocol {
switch environment {
case .dev:
return MockNetworkClient()
case .staging:
return NetworkClient(baseURL: "https://staging.api.com")
case .production:
return NetworkClient(baseURL: "https://api.com")
}
}
}
// Caller doesn't care which type comes back
let client = NetworkClientFactory.make(for: .production)
// Factory method on a protocol
protocol ViewControllerFactory {
func makeLoginViewController() -> UIViewController
func makeHomeViewController() -> UIViewController
}
Rate your understanding: