How can I implement an abstract singleton class in Java?

前端 未结 6 441
日久生厌
日久生厌 2020-12-15 16:48

Here is my sample abstract singleton class:

public abstract class A {
    protected static A instance;
    public static A getInstance() {
        return ins         


        
6条回答
  •  天涯浪人
    2020-12-15 17:43

    A.getInstance() will never call a derived instance since it's statically bound.

    I would separate the creation of the object from the actual object itself and create an appropriate factory returning a particular class type. It's not clear how you'd parameterise that, given your example code - is it parameterised via some argument, or is the class selection static ?

    You may want to rethink the singleton, btw. It's a common antipattern and makes testing (in particular) a pain, since classes under test will provide their own instance of that class as a singleton. You can't provide a dummy implementation nor (easily) create a new instance for each test.

提交回复
热议问题