Easy manufacturing facility implementation utilizing switch-case
The objective of this sample is to encapsulate one thing that may typically fluctuate. Think about a coloration palette for an software. You might need to alter the colours in accordance with the newest behavior of the designer every day. I might be actually inconvenient in the event you needed to search & substitute each single occasion of the colour code by hand. So let’s make a easy manufacturing facility in Swift that may return colours primarily based on a given fashion. 🎩
class ColorFactory {
enum Fashion {
case textual content
case background
}
func create(_ fashion: Fashion) -> UIColor {
swap fashion {
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 an advanced object initialization course of. You can too outline a protocol and return varied occasion sorts that implement the required interface utilizing a swap case block. 🚦
protocol Surroundings {
var identifier: String { get }
}
class DevEnvironment: Surroundings {
var identifier: String { return "dev" }
}
class LiveEnvironment: Surroundings {
var identifier: String { return "dwell" }
}
class EnvironmentFactory {
enum EnvType {
case dev
case dwell
}
func create(_ sort: EnvType) -> Surroundings {
swap sort {
case .dev:
return DevEnvironment()
case .dwell:
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 may be carried out in Swift utilizing an enum and a switch-case
- use a protocol if you’re planning to return completely different objects (POP 🎉)
- preserve 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 depart all of your assessments and every thing else utterly untouched. Highly effective and easy! 💪