0

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
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Matloob Hasnain
  • 1,025
  • 6
  • 21
  • I can still do this `let myTheme = LightTheme(backgroundColor: .gray, textColor: .red)` and then there are 3 variants. Or create a new type that conforms to `Theme`. – Joakim Danielson Jul 24 '23 at 11:14

0 Answers0