Swift easy manufacturing unit design sample


Easy manufacturing unit implementation utilizing switch-case

The purpose of this sample is to encapsulate one thing that may typically fluctuate. Think about a coloration palette for an utility. You may need to vary the colours in line with the most recent behavior of the designer each day. I might be actually inconvenient when you needed to search & substitute each single occasion of the colour code by hand. So let’s make a easy manufacturing unit in Swift that may return colours based mostly on a given model. 🎩

class ColorFactory {

    enum Fashion {
        case textual content
        case background
    }

    func create(_ model: Fashion) -> UIColor {
        change model {
        case .textual content:
            return .black
        case .background:
            return .white
        }
    }
}


let manufacturing unit = ColorFactory()
let textColor = manufacturing unit.create(.textual content)
let backgroundColor = manufacturing unit.create(.background)

This may be actually helpful, particularly if it involves an advanced object initialization course of. You can even outline a protocol and return varied occasion sorts 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 "reside" }
}

class EnvironmentFactory {

    enum EnvType {
        case dev
        case reside
    }

    func create(_ kind: EnvType) -> Atmosphere {
        change kind {
        case .dev:
            return DevEnvironment()
        case .reside:
            return LiveEnvironment()
        }
    }
}

let manufacturing unit = EnvironmentFactory()
let dev = manufacturing unit.create(.dev)
print(dev.identifier)

So, a number of issues to recollect in regards to the easy manufacturing unit design sample:

  • it helps free coupling by separating init & utilization logic 🤔
    • it is only a wrapper to encapsulate issues that may change typically 🤷‍♂️
    • easy manufacturing unit will 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 🎉)
    • maintain it easy 🏭

This sample separates the creation from the precise utilization and strikes the duty to a particular function, so if one thing adjustments you solely have to change the manufacturing unit. You possibly can depart all of your exams and every thing else fully untouched. Highly effective and easy! 💪

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox