iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 9
0
自我挑戰組

Pro Design Patterns in Swift5系列 第 9

Day9: Chapter6: Singleton 模式(上)

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20200924/20130138EuENbaSfMQ.jpg

Photo by Gunnar Ridderström on Unsplash


Singleton 模式可確保應用程式中的指定型別只會出現一個物件

import Foundation

class DataItem {
    enum ItemType: String {
        case Email = "Email Address";
        case Phone =  "Telephone";
        case Card = "Credit Card Number";
    }
    
    var type: ItemType;
    var data: String;
    
    init(type: ItemType, data: String) {
        self.type = type;
        self.data = data;
    }
}

class BackupServer {
    let name: String;
    private var data = [DataItem]();
    
    init(name: String) {
        self.name = name;
    }
    
    func backup(item: DataItem) {
        data.append(item)
    }
    
    func getData() -> [DataItem] {
        return data;
    }
}

var server = BackupServer(name: "Server#1");
server.backup(item: DataItem(type: DataItem.ItemType.Email, data: "joe@example.com"));
server.backup(item: DataItem(type: DataItem.ItemType.Phone, data: "555-123-1133"));

var otherServer = BackupServer(name: "Server#2");
otherServer.backup(item: DataItem(type: DataItem.ItemType.Email, data: "bob@example.com"));

// 程式列 6-3

class Logger {
    private var data = [String]()
    
    func log(msg: String) {
        data.append(msg);
    }
    
    func printLog() {
        for msg in data {
            print("Log: \(msg)")
        }
    }
}

程式列 6-4 pass
程式列 6-5 pass
程式列 6-6 init() 不加 private
程式列 6-7 pass
程式列 6-8 pass
程式列 6-9 init() 不加 private
程式列 6-10 pass

程式列 6-11 //歡迎提供 issue feedback, thank you.

var server = BackupServer.server;

let queue = DispatchQueue(label: "workQueue", qos: .default, attributes: .concurrent);
let group = DispatchGroup();

for _ in 0 ..< 100 {
    queue.async {
        BackupServer.server.backup(item: DataItem(type: DataItem.ItemType.Email, data: "bob@example.com"))
    }
    _ = group.wait(timeout: .now())
    
    print("\(server.getData().count)")
}

用底線消除 Swift 3 的忽略回傳值警告
https://www.appcoda.com.tw/grand-central-dispatch/

程式列 6-13 黑體字

private let arratyQ = DispatchQueue(label: "arrayQ");
DispatchQueue.main.sync(execute: {
            data.append(item);
            globalLogger.log(msg: "\(name) backed up item of type \(item.type.rawValue)");
        })

小鴨鴨妳是不是也遇到難解的bug

https://ithelp.ithome.com.tw/upload/images/20200925/20130138ZOIYor40pI.jpg
Photo by CS50

才第9天我怎麼變這樣QQ


上一篇
Day8: Prototype 模式(下)
下一篇
Day10:
系列文
Pro Design Patterns in Swift517
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言