Sababado
Sababado

Reputation: 2532

Java: Inherit and Be a Singleton

To begin with, I am NOT trying to create a subclass of a singleton class. (At least I'm sure I'm not trying to).

I have a class ClassA that is abstract.

I have two classes, ClassA1 and ClassA2 that extend ClassA.

I want ClassA1 and ClassA2 to be singleton classes. I could just write the code in each one to do so but I would prefer to write the code once in ClassA and reuse it in all of it's sub-classes. Is there a way to do this?

Upvotes: 4

Views: 2356

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109567

The only place this is done is in the enum classes which extend Enum. It uses a language twist, and something like class ClassA<T extends ClassA>. Either you do:

public class ClassA {

    private static final Map<Class<? extends ClassA>, ClassA> singletons = new HashMap<>();

    public static <T extends ClassA> T get(Class<T> klazz) {
        T singleton = klazz.cast(singletons.get(klazz));
        if (singleton == null) {
            try {
                singleton = klazz.getConstructor().newInstance();
            } catch (InstantiationException | IllegalAccessException
                    | IllegalArgumentException | InvocationTargetException
                    | NoSuchMethodException | SecurityException e) {
                throw new IllegalArgumentException(e);
            }
            singletons.put(klazz, singleton);
        }
        return singleton;
    }
    protected ClassA() { }
}

Or you rethink your desire of plural singletons, and either do a general container lookup, (maybe with declarative XML or annotations) or a bean container. EJB 3.1 is very nice and simple.

Upvotes: 1

Scorpion
Scorpion

Reputation: 3976

I would suggest private constructors for ClassA1 and A2 and having static methods for object creation. This way you have complete control over object creation. The book EffectiveJava details out the adavatages of this approach.

Upvotes: 1

Rob I
Rob I

Reputation: 5737

Probably not - the singleton pattern requires static methods/fields, which would be shared by ClassA and all its subclasses if defined in one place.

Upvotes: 6

Related Questions