How to get other classes to get one class?

I apologize if this is a duplicate or too elementary, but how to create a singleton class that can be subclassed?

+5
source share
6 answers

Steve Egg has a fun article on singles that mentions a subclass in this quote:

Then there is a subclassification. It is almost impossible to subclass Singleton, and if you could handle it, then you shouldn't have used Singleton in the first place. You don’t even want to go there. I which I dare not retell. Just pretend you can't do this and you will save yourself stunning amounts of pain.

+11
source

, . Singleton.

+5

, , .

singleton, (s) private. , ... ; .

public class A () {
    private A() { }
}

public class B () {
    private B() { }
}

Sun JDK 1.6 Eclipse Ganymede B, no-args A .

private, ( ), - . , .

EDIT: , ( ) /, , . , .

+3

:

public class Singleton {
  private static Singleton instance;
  public static Singleton getInstance() {
     if (instance == null) {
       instance = new Singleton();
     }
     return instance;
  }
  private Singleton() {
  }
}

:

public class NewSingleton extends Singleton {
}

, , , Singleton.getInstance();, , .

, .

, Singleton, AspectJ / Singleton, Singleton.

+1

Singleton , . , , , ( , ). ?

+1

, . singleton, singleton. , .

; , , , , - :

public static synchronised Singleton getInstance() {
    if (instance == null) {
        String clsName = System.getProperties().getProperty("singleton.class");
        if (className == null || 0 == clasName.length()) {
            instance = new Singleton();
        } else {
            Class cls = Class.forName(clsName);
            instance = (Singleton) cls.newInstance();
        }
     }
     return instance;
}

: , ..:-) Btw, , getInstance() .

0

All Articles