1、饿汉单例模式
饿汉单例模式在类加载的时候立即初始化,并且创建单例对象,绝对线程安全,线程还没出现之前就进行了实例化,不会存在访问安全问题
优点:没有加任何锁,执行效率比较高,用户体验更好
缺点:类加载的时候就初始化,用于不用都占用空间,浪费内存。
(1) 基于静态类的初始化
public class HungrySingleton {
private static final HungrySingleton hungrySingleton = new HungrySingleton();
private HungrySingleton(){}
public static HungrySingleton getInstance(){
return hungrySingleton;
}
}
(2) 基于静态代码块的初始化
public class HungryStaticSingleton {
private static final HungryStaticSingleton hungrySingleton;
static {
hungrySingleton = new HungryStaticSingleton();
}
private HungryStaticSingleton(){}
public HungryStaticSingleton getInstance(){
return hungrySingleton;
}
}
2、懒汉单例模式
懒汉单例模式的特点是:被外部类调用的时候内部类才会加载
懒汉单例模式的简单实现
public class LazySimpleSingleton {
private LazySimpleSingleton(){}
public static LazySimpleSingleton lazySimpleSingleton = null;
public static LazySimpleSingleton getInstance(){
if (lazySimpleSingleton == null){
lazySimpleSingleton = new LazySimpleSingleton();
}
return lazySimpleSingleton;
}
}
这种创建对象可能会出现线程安全问题,创建出不同的对象
可以选择给getInstance加上synchronized关键字,使这个方法变成线程同步方法
public class LazySimpleSingleton {
private LazySimpleSingleton(){}
public static LazySimpleSingleton lazySimpleSingleton = null;
public synchronized static LazySimpleSingleton getInstance(){
if (lazySimpleSingleton == null){
lazySimpleSingleton = new LazySimpleSingleton();
}
return lazySimpleSingleton;
}
}