Using the factory method pattern

Let's see how we can leverage the factory method pattern in order to improve existing code.

Let's say you're building an app that let users poke, message, or call their contacts, as follows:

 enum ContactAction {    case call    case message    case poke}class ContactController: NSViewController {    let callButton = NSButton(title: "Call", target: self, action: #selector(processAction(from:)))    let messageButton = NSButton(title: "Message", target: self, action: #selector(processAction(from:)))    let pokeButton = NSButton(title: "Poke", target: self, action: #selector(processAction(from:)))        private func action(for button: NSButton) -> ContactAction {        switch button {        case callButton:            return .call        case messageButton:            return ...

Get Hands-On Design Patterns with Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.