开发者

Java singleton with inheritance

开发者 https://www.devze.com 2023-03-12 05:54 出处:网络
I have a set of singleton classes and I want to avoid boilerplate code. Here is what I have now: public class Mammal {

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?


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.


You can use enum to create singletons.

public enum Mammal {
    Cat {
        // put custom fields and methods here
    }
}


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号