Swift summary manufacturing unit design sample


Summary manufacturing unit in Swift

The summary manufacturing unit sample gives a method to encapsulate a gaggle of particular person factories which have a typical theme with out specifying their concrete lessons.

So summary manufacturing unit is there so that you can create households of associated objects. The implementation often combines easy manufacturing unit & manufacturing unit methodology ideas. Particular person objects are created by manufacturing unit strategies, whereas the entire thing is wrapped in an “summary” easy manufacturing unit. Now test the code! 😅


protocol ServiceFactory {
    func create() -> Service
}

protocol Service {
    var url: URL { get }
}


class StagingService: Service {
    var url: URL { return URL(string: "https://dev.localhost/")! }
}

class StagingServiceFactory: ServiceFactory {
    func create() -> Service {
        return StagingService()
    }
}


class ProductionService: Service {
    var url: URL { return URL(string: "https://dwell.localhost/")! }
}

class ProductionServiceFactory: ServiceFactory {
    func create() -> Service {
        return ProductionService()
    }
}


class AppServiceFactory: ServiceFactory {

    enum Atmosphere {
        case manufacturing
        case staging
    }

    var env: Atmosphere

    init(env: Atmosphere) {
        self.env = env
    }

    func create() -> Service {
        change self.env {
        case .manufacturing:
            return ProductionServiceFactory().create()
        case .staging:
            return StagingServiceFactory().create()
        }
    }
}

let manufacturing unit = AppServiceFactory(env: .manufacturing)
let service = manufacturing unit.create()
print(service.url)

As you possibly can see utilizing an summary manufacturing unit will affect the entire software logic, whereas manufacturing unit strategies have results solely on native components. Implementation can range for instance you possibly can additionally create a standalone protocol for the summary manufacturing unit, however on this instance I needed to maintain issues so simple as I may.

Summary factories are sometimes used to attain object independence. For instance when you have a number of totally different SQL database connectors (PostgreSQL, MySQL, and so on.) written in Swift with a typical interface, you possibly can simply change between them anytime utilizing this sample. Similar logic may very well be utilized for something with the same state of affairs. 🤔

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