2

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.

  • 1
    I'd love to answer this question but despite the fact that I've studied Pure Dependency Injection in depth and used it professionally the only answer I have for you is: Yes, you got it. – candied_orange Oct 29 '19 at 1:21
  • Thanks for the confirmation! – peaxol Oct 29 '19 at 21:52
  • Welcome. Wish I could offer more but your question shows you have the concept down. Doesn't leave me much room to add anything – candied_orange Oct 29 '19 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.