lundi 21 décembre 2015

Service Locator pattern in Swift

I'm interested in a flexible universal Service Locator design pattern implementation in Swift.

A naive approach may be as follows:

// Services declaration

protocol S1 {
    func f1() -> String
}

protocol S2 {
    func f2() -> String
}

// Service Locator declaration
// Type-safe and completely rigid.

protocol ServiceLocator {
    var s1: S1? { get }
    var s2: S2? { get }
}

final class NaiveServiceLocator: ServiceLocator {
    var s1: S1?
    var s2: S2?
}

// Services imlementation

class S1Impl: S1 {
    func f1() -> String {
        return "S1 OK"
    }
}

class S2Impl: S2 {
    func f2() -> String {
        return "S2 OK"
    }
}

// Service Locator initialization

let sl: ServiceLocator = {
    let sl = NaiveServiceLocator()
    sl.s1 = S1Impl()
    sl.s2 = S2Impl()
    return sl
}()

// Test run

print(sl.s1?.f1() ?? "S1 NOT FOUND") // S1 OK
print(sl.s2?.f2() ?? "S2 NOT FOUND") // S2 OK

But it would be much better if the Service Locator will be able to handle any type of service without changing its code. How this can be achieved in Swift?

Note: the Service Locator is a pretty controversial design pattern (even called an anti-pattern sometimes), but please let's avoid this topic here.

Aucun commentaire:

Enregistrer un commentaire