Java singleton with inheritance

I have a set of singleton classes and I want to avoid the template 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 is nothing wrong with that, except that I have many Mammal subclasses that the getInstance() method should replicate. 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 to do it?

+8
java code-formatting inheritance singleton
source share
3 answers

You cannot, because constructors are not inherited or redefined. new Mammal() in your desired example creates only Mammal , not one of its subclasses. I suggest you look at the Factory template or go to something like Spring, which is designed only for this situation.

+3
source share

You can use enum to create singletons.

 public enum Mammal { Cat { // put custom fields and methods here } } 
+2
source share

Make your constructor private, this will prevent your class from inheriting from other classes.

Or the best way to create a singleton is to create your class with a single enumeration. (Josh block)

0
source share

All Articles