簡體   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