HomeiOS DevelopmentSwift easy manufacturing facility design sample

Swift easy manufacturing facility design sample


Easy manufacturing facility implementation utilizing switch-case

The objective of this sample is to encapsulate one thing that may usually differ. Think about a coloration palette for an software. You might need to alter the colours based on the most recent behavior of the designer each day. I would be actually inconvenient should 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 based mostly on a given type. 🎩

class ColorFactory {

    enum Model {
        case textual content
        case background
    }

    func create(_ type: Model) -> UIColor {
        change type {
        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 too outline a protocol and return numerous occasion varieties that implement the required interface utilizing a change 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(_ kind: EnvType) -> Surroundings {
        change kind {
        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 usually 🤷‍♂️
  • easy manufacturing facility might 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 selected function, so if one thing adjustments you solely have to switch the manufacturing facility. You may depart all of your assessments and all the pieces else utterly untouched. Highly effective and easy! 💪

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments