单例设计模式(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
网友评论