1.懒汉式
public class Singleton {
private static Singleton instance = null;
private Singleton(){}
//如果还没有被实例化过,就实例化一个,然后返回
public static synchronized Singleton getInstance(){
if (instance==null)
instance = new Singleton();
return instance;
}
}
2.饿汉式
public class Singleton1 {
//类加载的时候instance就已经指向了一个实例
private static Singleton1 instance = new Singleton1();
private Singleton1(){}
public static Singleton1 getInstance(){
return instance;
}
}
3.双重检验锁
public class Singleton2 {
private static Singleton2 instance = null;
private Singleton2(){}
public static Singleton2 getInstance(){
if (instance==null){
synchronized (Singleton2.class){
if (instance==null)
instance = new Singleton2();
}
}
return instance;
}
}
4.静态内部类
因为JAVA静态内部类的特性,加载的时候不会加载内部静态类,使用的时候才会加载,而使用的时候类加载又是线程安全的,这就完美达到了效果;
public class Singleton3 {
private static class SingletonHolder{
private static Singleton3 instance = new Singleton3();
}
private Singleton3(){}
public Singleton3 getInstance(){
return SingletonHolder.instance;
}
}
5.枚举
public enum Singleton {
INSTANCE;
}