singleton , , , , .
,
public class Singleton {
private static Singleton theInstance = new Singleton();
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
return theInstance;
}
}
public class FakeSingleton {
private static int aVar = 10;
public static void aMethod() {
System.out.println(aVar);
}
}
( Singleton.getInstance().aMethod()
FakeSingleton.aMethod()
).
, , , , :
public class Singleton {
private static Singleton theInstance = null;
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
if (theInstance == null) {
theInstance = new Singleton();
}
return theInstance;
}
}
(Note that the above is not thread safe, in multi-threaded code you will need to add synchronization.)
source
share