public class Singleton{
private Singletion(){}
private static Singleton Instance;
public static Singeton getInstance(){
if(Instance==null){
Instance = new Singleton();
}
return Instance;
}
}
懒汉式(安全低效率)
public class Singleton{
private Singletion(){}
private static Singleton Instance;
public static Synchronizeed Singeton getInstance(){
if(Instance==null){
Instance = new Singleton();
}
return Instance;
}
}
恶汉式
public class Singleton{
private Singletion(){}
private static Singleton Instance = new Singleton();
public static Singeton getInstance(){
return Instance;
}
}
懒汉式(双校验)
public class Singleton{
private Singletion(){}
private static Singleton Instance;
public static Singeton getInstance(){
if(Instance==null){
Synchronizeed(Singleton.class){
if(Instance==null){
Instance = new Singleton();
}
}
}
return Instance;
}
}
懒汉式(静态式)
public class Singleton{
private Singletion(){}
private static final class SingletonHolder {
private final Singleton instance = new Singleton();
}
public static Singeton getInstance(){
return SingletonHolder.instance;
}
}
枚举
public enum Singleton{
Instance;
public void doMethod(){};
}