hb ~/posts/monostate-or-singleton-with-a-twist-design-pattern 2023

article

Monostate or "Singleton with a twist" design pattern

/ 1 min read
all posts
portfolio / design patterns

The Monostate design pattern is a creational pattern that ensures all instances of a class share the same state, while still allowing multiple instances to be created.

This pattern is also known as the "Singleton with a twist" pattern, as it provides similar functionality to the Singleton pattern, but with a different approach to maintaining shared state.

class EuropeUnion {
    private static var sharedState: String = "Normal activity"

    var state: String {
        get { return EuropeUnion.sharedState }
        set { EuropeUnion.sharedState = newValue }
    }
}

let ueInstance = EuropeUnion()
ueInstance.state = "Lockdown due to Covid-19"

let ueInstance2 = EuropeUnion()
print(ueInstance2.state)


// Germany shares the same state as EuropeUnion
class Germany: EuropeUnion {}
let germanyInstance = Germany()
print(germanyInstance.state)

// Italy shares the same state as EuropeUnion
class Italy: EuropeUnion {}
let italyInstance = Italy()
print(italyInstance.state)

As you can see, the Monostate design pattern can be useful in situations where you have a class that contains global application state that needs to be shared across multiple objects.

Check my GitHub repos about design patterns with Swift: github.com/HaraldBregu