Singleton Patternのいくつかの方法
1276 ワード
public class Singleton {
private final static Singleton instance = new Singleton();
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
public class Singleton {
private static Singleton instance;
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
private static class SingletonHolder {
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
public class Singleton {
private volatile static Singleton instance;
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}