设计模式与软件原则 (二):单例设计模式

2022-02-22  本文已影响0人  _浅墨_
单例设计模式(Singleton Design Pattern)

单例设计模式是一种创造(creational)设计模式。它确保一个单例类在全局只有一个对象。

import UIKit

enum ThemeSetting {
    
    case darkMode, lightMode
    
    var description: String {
        
        switch self {
            case .darkMode:
                return "Dark mode is active"
                
            case .lightMode:
                return "Light mode is active"
        }
    }
    
}


class Settings {
    
    static let shared = Settings()
    
    private(set) var theme: ThemeSetting = .lightMode
    private(set) var font = UIFont.systemFont(ofSize: 12)
    
    private init() {
        
    }
    
    func changeTheme(to theme: ThemeSetting) {
        self.theme = theme
    }
    
    func changeFontSize(to fontSize: Int) {
        self.font = UIFont.systemFont(ofSize: CGFloat(fontSize))
    }
    
}

Settings.shared.theme.description

Settings.shared.changeTheme(to: .darkMode)

Settings.shared.theme.description

上一篇下一篇

猜你喜欢

热点阅读