jeudi 3 janvier 2019

Swift Mediator Pattern - Array of generic protocols

I am trying to implement a general-purpose Mediator pattern in Swift and have the following protocols and classes:

// General Purpose protocols and class(es)

protocol Request {
}

protocol Handler {
    associatedtype TRequest = Request

    func handle(_ request: TRequest)
}

class RequestProcessor {

    func register<THandler: Handler>(_ handler: THandler) {

    }

    func handle(_ request: Request) {

    }

}

With the intended usage being (for example):

struct LoginRequest: Request {
    let username: String
    let password: String
}

struct LogoutRequest: Request {
    let userId: Int
}

class LoginHandler: Handler {
    func handle(_ request: LoginRequest) {
        // do something
    }
}

class LogoutHandler: Handler {
    func handle(_ request: LogoutRequest) {
        // do something
    }
}

// Setup the processor and register handlers

let processor = RequestProcessor()
processor.register(LoginHandler())
processor.register(LogoutHandler())

// The processor handles any kind of Request, in this case a LoginRequest

processor.handle(LoginRequest(username: "steve", password: "..."))

However I'm not sure how to store the collection of Handler objects since it is a protocol with associated type. I am aware of type-erasure and have read several answers here as well as various articles on the subject (1, 2) but am unsure how to apply it to my situation.

Aucun commentaire:

Enregistrer un commentaire