繁体   English   中英

Swift 3.0 工厂设计模式的实现

[英]Implementation of Factory design pattern in Swift 3.0

我想在Swift 3.0 中实现工厂设计模式

我正在考虑的基本解决方案是:

这是一个合理的方法吗?

或者 Swift 中是否有其他设计模式?

您可以尝试使用此实现作为参考。 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)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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