Java单例模式(饿汉式和懒汉式)
单例模式:提供了一种创建对象的最佳方式
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
1. 饿汉式
1)类加载时就创建了对象实例
2)不存在线程安全问题
3)可能会浪费资源
public class Hungry {
private Hungry(){}
**private final static Hungry HUNGRY = new Hungry();**
public static Hungry getInstance(){
return new Hungry();
}
}
2. 懒汉式
1)调用获取实例对象方法时才创建
2)存在线程安全问题
public class LazyMan {
private LazyMan(){
System.out.println(Thread.currentThread().getName()+"OK");
}
**private volatile static LazyMan lazyMan;**
public static LazyMan getInstance(){
if (lazyMan == null){
synchronized (LazyMan.class){
if (lazyMan == null){
lazyMan = new LazyMan();
}
}
}
return lazyMan;
}
}