jgr208
jgr208

Reputation: 3066

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();
    }
}

Upvotes: 0

Views: 157

Answers (2)

Bubletan
Bubletan

Reputation: 3863

Well something like this is possible:

public final class Singletons {

    private static final Map<Class<?>, Object> map = new HashMap<>();

    private Singletons() {
    }

    public static <T> T get(Class<T> type) {
        Object instance = map.get(type);
        if (instance != null) {
            return (T) instance;
        }
        synchronized (map) {
            instance = map.get(type);
            if (instance != null) {
                return (T) instance;
            }
            try {
                instance = type.newInstance();
            } catch (Exception e) {
                throw new IllegalArgumentException("error creating instance");
            }
            map.put(type, instance);
            return (T) instance;
        }
    }
}

Then you could do just:

FooDataWriter instance = Singletons.get(FooDataWriter.class);

Upvotes: 0

Paul Boddington
Paul Boddington

Reputation: 37645

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!

Upvotes: 2

Related Questions