示例如下:
/*
* 懒汉式
//1 懒汉式 时间换空间(可能出现线程安全问题-直接在获取单例对象的方法上加synchronized)
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
//解决线程安全问题方法如下(双重检验懒汉单例模式DCL,可能会出现对象半初始化问题,
需要再对象引用命名的位置使用volatail修改,防止指令重排),理解内存屏障
public static Singleton getSynInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
*/
/*
//2 饿汉式 空间换时间
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
*/
//3 通过内部类创建
private static class SingletonInner{
private static Singleton instance = new Singleton();
}
private Singleton(){};
public static Singleton getInstance(){
return SingletonInner.instance;
}