How can I implement an abstract singleton class in Java?

前端 未结 6 442
日久生厌
日久生厌 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:38

    Singletons are kind of yucky. Abstract insists on inheritance which you more often than not want to avoid if possible. Overall I'd rethink if what you are trying to do is the simplest possible way, and if so, then be sure to use a factory and not a singleton (singletons are notoriously hard to substitute in unit tests whereas factories can be told to substitute test instances easily).

    Once you start looking into implementing it as a factory the abstract thing will sort itself out (either it will clearly be necessary or it may factor out easily in place of an interface).

提交回复
热议问题