I have been using singletons in the past. However, reading articles like Singletons are Pathological Liars have led me to explore alternatives to singletons.
There are a few posts discussion alternatives such as: So Singletons are bad, then what?
I am not able to get a concrete example on how to convert though.
Here is my scenario: I am working on a monitoring application which creates and updates alarms based on cluster state. These alarms are created based on certain rules and can be updated/closed etc via an API exposed to the user. Snippet of the structure for alarms in Go is:
type alarm struct {
state string
duration time.Duration
}
type alarms map[string]alarm // Map of alarmId : alarm
I was planning a singleton alarms struct(class) since it needs to be accessed from various places - created based on cluster state, modified via APIs etc and each caller should see the same state of alarms. I.e. effectively only one instance of alarms should be present through the application lifetime.
A singleton would be:
var once sync.Once
var instance *SingletonAlarm
func Load() *SingletonAlarm {
once.Do(func() {
instance = &SingletonAlarm{}
})
return instance
}
If I leave it as a singleton, each package like webserver etc would independent call Load and get the same instance.
If I move to single instance paradigm, would these be the steps to do it:
i) Create the single instance of alarm (say in main)
ii) Then for every structure(class) that needs this, add a field for alarms and pass it in when that struct is initialized (dependency injection)? Thus the struct in webserver would now have a field for alarms which gets populated as mentioned above.