Swift: Factory Pattern
Factory Pattern is a creational design pattern, which helps in hiding the creational logic rather than creating the concrete type at the consumer end. Instead of directly providing the created concrete type, It can also help in hiding the created concrete type by providing the abstracted type to the consumer.
In order to explain the factory pattern, we are considering the scenario of creating the base URL and CDN URL.
First, we are creating a protocol named URLService, which contains declarations for baseURL and cdnURL. This protocol is created so that we could define the properties for each environment
protocol URLService {
var baseURL: URL { get }
var cdnURL: URL { get }
}
For simplicity purposes, we are assuming only two environments Dev and Prod. We are creating two classes that conform to URLService for both dev & Prod named as DevURLService and ProdURLService respectively.
class DevURLService: URLService {
var baseURL: URL { return URL(string: "https://dev.domain.com")! }
var cdnURL: URL { return URL(string: "https://dev.CDN-domain.com")! }
}
class ProdURLService: URLService {
var baseURL: URL { return URL(string: "https://domain.com")! }
var cdnURL: URL { return URL(string: "https://CDN-domain.com")! }
}
After the creation of DevURLService and ProdURLService, it is time for the creation of the factory which is named URLFactory. This URLFactory has an enum Environment which comprises of values dev and prod. We then have a method create which takes the type of Environment(Enum which contains dev and prod as it's cases) as a parameter and then creates & returns the appropriate URLService instance.
class URLFactory {
enum Environment {
case dev
case prod
}
func create(environment: Environment) -> URLService {
if environment == .dev {
return DevURLService()
} else {
return ProdURLService()
}
}
}
//USAGE:
let urlService = URLFactory().create(environment: .dev)
print(urlService.baseURL)
print(urlService.cdnURL)
Under the Usage, you could see that we could get the URLService by creating an instance for URLFactory and then invoking the create method by specifying the environment.
In the above example, we had successfully hidden the creation logic(Service corresponding to the environment). Since we are returning the abstraction URLService, we are also not exposing the concrete environment-based service type( DevURLService & ProdURLService).
Well, That's a wrap for this article. Hope you got the idea behind the factory pattern and start implementing it in your apps. Happy Coding!!!