饿汉式
public class SingletonOne {
private static SingletonOne instance = new SingletonOne();
private SingletonOne(){}
public static SingletonOne getInstance(){
return instance;
}
}
Runtime类
懒汉式
public class SingletonTwo {
private static SingletonTwo instance;
private SingletonTwo(){}
public static synchronized SingletonTwo getInstance(){
if (instance == null)
instance = new SingletonTwo();
return instance;
}
}
静态内部类
public class SingletonThree {
private static class Singleton{
private static SingletonThree instance = new SingletonThree();
}
private SingletonThree(){}
public static SingletonThree getInstance(){
return Singleton.instance;
}
}
枚举类
public class SingletonFour {
private SingletonFour(){}
private static enum Singleton{
instance;
private SingletonFour singletonFour;
private Singleton(){
singletonFour = new SingletonFour();
}
public SingletonFour getInstance(){
return singletonFour;
}
}
public static SingletonFour getInstance(){
return Singleton.instance.getInstance();
}
}