SLaks
SLaks

Reputation: 887215

Multi-variable complicated singletons

I have a pair of static fields with a complicated one-time initialization. I want this initialization to happen lazily, a la the standard singleton pattern.

However, the initialization procedure involves both fields, so I can't separate it into two different singletons.

What's the best way to handle this?

Upvotes: 0

Views: 181

Answers (2)

SLaks
SLaks

Reputation: 887215

I'm currently doing it like this:

class OuterType {
    //...

    static class FieldInitializer {
        public static readonly SomeType field1, field2;

        static FieldInitializer() {
            //Complicated code that sets both fields together
        }
    }

    //...
}

Does anyone have any other ideas?

Upvotes: 0

jerryjvl
jerryjvl

Reputation: 20121

Create a wrapper class that contains the references to both your 'singletons' and make that class the singleton?

Addendum:
If you really want to avoid the second level of indirection with this approach, you can always do it in two stages:

  • create a new singleton that encapsulates the individual singletons (original point)
  • create a singleton for each of the original singletons (with separate backing fields) that is initialised from the combined singleton to guarantee that all singletons are initialised atomically

Upvotes: 1

Related Questions