Java: Inherit and be singleton

For starters, I am NOT trying to subclass a singleton class. (At least I'm sure I'm not trying).

I have a class ClassAthat is abstract.

I have two classes, ClassA1and ClassA2that extend ClassA.

I want to ClassA1and ClassA2were singletons. I could just write code in each to do this, but I would rather write the code once in ClassAand reuse it in all its subclasses. Is there any way to do this?

+3
source share
3 answers

, - singleton /, ClassA , .

+6

ClassA1 A2 . , . EffectiveJava .

+1

The only place this is done is the enum classes that extend Enum. It uses a language twist and something like that class ClassA<T extends ClassA>. Or 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() { }
}

Either you rethink your desire for plural singles and do a general search for containers (possibly with declarative XML or annotations) or in a bean container. EJB 3.1 is very nice and simple.

+1
source

All Articles