Multiton Design Pattern in swift (multi singleton)

62 Views Asked by At

I am trying to implement multi theme inside application with the help of multiton design patterns. I never implemented multiton before. Please have a look is it prefect implementation or we can implement in some better way.

import UIKit
    
protocol Theme: Equatable {
  var backgroundColor: UIColor { get }
  var textColor: UIColor { get }
}
    
struct LightTheme: Theme {
  var backgroundColor: UIColor = .white
  var textColor: UIColor = .black 
} 

struct Dark Theme: Theme {
  var backgroundColor: UIColor = .black
  var textColor: UIColor = .white 
}
    
func == (1hs: any Theme, rhs: any Theme) -> Bool {
  return lhs.backgroundColor == rhs.backgroundColor &&
    1hs.textColor == rhs.textColor 
}


// Make ThemeManager a struct for value semantics.
struct ThemeManager {
    enum ThemeColor {
        case light
        case dark
    }

    private init() {}
    static var shared = ThemeManager ()
    private var themes: [ThemeColor: any Theme] = [
        .light: Light Theme (),
        .dark: DarkTheme ( )
    ]
    func theme (for themeColor: ThemeColor) -> any Theme {
        return themes [themeColor] ?? LightTheme()
    }
}
// Usage:
let light Theme = ThemeManager.shared.theme (for: .light)
let darkTheme = ThemeManager.shared.theme (for: .dark)
let anotherLightTheme = ThemeManager.shared.theme (for: .light)
print (light Theme == anotherLightTheme) // Output: true
print (light Theme == darkTheme) // Output: false
0

There are 0 best solutions below