Easy manufacturing facility implementation utilizing switch-case
The purpose of this sample is to encapsulate one thing that may typically range. Think about a coloration palette for an software. You might need to alter the colours in line with the most recent behavior of the designer each day. I might be actually inconvenient in the event you needed to search & change each single occasion of the colour code by hand. So let’s make a easy manufacturing facility in Swift that may return colours based mostly on a given model. 🎩
class ColorFactory {
enum Model {
case textual content
case background
}
func create(_ model: Model) -> UIColor {
change model {
case .textual content:
return .black
case .background:
return .white
}
}
}
let manufacturing facility = ColorFactory()
let textColor = manufacturing facility.create(.textual content)
let backgroundColor = manufacturing facility.create(.background)
This may be actually helpful, particularly if it involves a sophisticated object initialization course of. You can even outline a protocol and return varied occasion varieties that implement the required interface utilizing a change case block. 🚦
protocol Atmosphere {
var identifier: String { get }
}
class DevEnvironment: Atmosphere {
var identifier: String { return "dev" }
}
class LiveEnvironment: Atmosphere {
var identifier: String { return "stay" }
}
class EnvironmentFactory {
enum EnvType {
case dev
case stay
}
func create(_ sort: EnvType) -> Atmosphere {
change sort {
case .dev:
return DevEnvironment()
case .stay:
return LiveEnvironment()
}
}
}
let manufacturing facility = EnvironmentFactory()
let dev = manufacturing facility.create(.dev)
print(dev.identifier)
So, just a few issues to recollect in regards to the easy manufacturing facility design sample:
- it helps unfastened coupling by separating init & utilization logic 🤔
- it is only a wrapper to encapsulate issues that may change typically 🤷♂️
- easy manufacturing facility could be carried out in Swift utilizing an enum and a switch-case
- use a protocol in case you are planning to return completely different objects (POP 🎉)
- hold it easy 🏭
This sample separates the creation from the precise utilization and strikes the accountability to a selected function, so if one thing adjustments you solely have to change the manufacturing facility. You may go away all of your assessments and every little thing else fully untouched. Highly effective and easy! 💪