Search code examples
javadesign-patternssingletoncommon-code

Common class for singleton


I am currently writing a program in which about 12 classes need to be a singleton, due to that they are using a messaging service which needs different types. My question is, instead of basically copy and pasting the singleton code for each for creating an instance with only changing the class it makes an instance of. Is there someway to have a common code that is used for the singleton pattern, for any class that needs to create a singleton?

Here is the code to create one of the singletons,

public static void create()
{
    if(instance == null)
    {
        instance = new FooDataWriter();
    }
}

Solution

  • You have to copy and paste whatever code you are using to implement the singleton, but according to Effective Java (2nd edition, p.18) the best way to enforce a singleton is to use a one-element enum:

    public enum MySingleton {
        INSTANCE;
    
        // methods
    }
    

    If you do it this way there's almost nothing to copy and paste!