简体   繁体   中英

Implementation of Factory design pattern in Swift 3.0

I would like to implement the factory design pattern in Swift 3.0 .

The basic solution that I am thinking of is:

  • Define a protocol that define as object creation method
  • Implement the protocol within the Object

Is this a sound approach?

Or are there alternative design patterns in Swift?

You can try to use this implementation as a reference. https://redflowerinc.com/implementing-factory-design-pattern-in-swift/

import UIKit
import PlaygroundSupport

enum Maps : Int {
    case google = 1
    case apple
}

protocol Display {
    func showMap()
}

class Map {
    let type : Int = 0
    func showMap(type : Maps) -> Display {
        switch type {
        case Maps.apple :
            return AppleMap()
        case Maps.google :
            fallthrough
        default:
            return GoogleMap()
        }
    }
}

class AppleMap : Display {
    func showMap() {
        print("showing apple map")
    }
}

class GoogleMap : Display {
    func showMap() {
        print("showing google map")
    }
}

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = UILabel()
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        label.text = "Hello World!"
        label.textColor = .black

        view.addSubview(label)
        self.view = view

        let map = Map()
        map.showMap(type: Maps.google)
        map.showMap(type: Maps.apple)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM