Java singleton with inheritance
Asked Answered
H

3

8

I have a set of singleton classes and I want to avoid boilerplate code. Here is what I have now:

public class Mammal {
    protected Mammal() {}
}

public class Cat extends Mammal {
    static protected Cat instance = null;
    static public Cat getInstance() {
        if (null == instance) {
            instance = new Cat();
        }
        return instance;
    }

    private Cat() {
        // something cat-specific
    }
}

This works and there's nothing wrong with it, except that I have many subclasses of Mammal that must replicate the getInstance() method. I would prefer something like this, if possible:

public class Mammal {
    protected Mammal() {}

    static protected Mammal instance = null;

    static public Mammal getInstance() {
        if (null == instance) {
            instance = new Mammal();
        }
        return instance;
    }
}

public class Cat extends Mammal {
    private Cat() {
        // something cat-specific
    }
}

How do I do that?

Horsey answered 10/6, 2011 at 15:55 Comment(3)
Your singleton getInstance() method is not properly implemented -- in a multi-threaded environment you can end up with multiple instances being created!Accepted
Not an answer to your question, but your singleton pattern isn't thread-safe. There are examples in Java Concurrency in Practice.Haire
Is a singleton really the best approach here? Singletons are best used to represent services or other things that there really is only one instance in the real world. Make sure this pattern is really suited for your application domain because I will assume your code isn't really using cats and dogs. If singletons are appropriate, I recommend using Jim Garrison's solution of using Spring; spring beans are singleton by default.Megargee
K
3

You can't since constructors are neither inherited nor overridable. The new Mammal() in your desired example creates only a Mammal, not one of its subclasses. I suggest you look at the Factory pattern, or go to something like Spring, which is intended for just this situation.

Keeton answered 10/6, 2011 at 16:2 Comment(0)
D
3

You can use enum to create singletons.

public enum Mammal {
    Cat {
        // put custom fields and methods here
    }
}
Dunsany answered 10/6, 2011 at 16:6 Comment(0)
E
0

Make your Constructor private, this will prevent your class to be inherited by other classes.

Or the best way to create a singleton is by creating your class an enum with one enumeration.(Josh Block)

Ensepulcher answered 10/6, 2011 at 16:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.