1.饿汉式(不推荐)
//饿汉式单例
public class Hungry {
//会浪费内存
private byte[] data1 = new byte[1024*1024];
private String string = "aaa";
//私有化
private Hungry() {}
private final static Hungry HUNGRY = new Hungry();
public static Hungry getInstance() {
return HUNGRY;
}
}
private final static Hungry HUNGRY = new Hungry();
优点:类加载的时候就完成了实例化。不存在线程安全问题。
缺点:在类加载的时候就完成实例化,没有达到LazyLoading的效果。如果从位使用过这个实例,则会造成内存的浪费。
2.静态代码快(不推荐)
public class SingleStatic {
private static SingleStatic singleStatic;
//静态代码块,类加载时就实例化,不推荐
static {
singleStatic = new SingleStatic();
}
private SingleStatic() {
}
public static SingleStatic getInstance() {
return singleStatic;
}
}
3.懒汉式(线程不安全方式)
public class LazyMan {
//volatile保证原子性
private static LazyMan lazyMan;
private LazyMan() {}
public static LazyMan getInstance() {
if (null == lazyMan) lazyMan = new LazyMan();
return lazyMan;
}
}
4.双重检查(推荐使用)
public class LazyMan {
//volatile禁止指令重排序
private static volatile LazyMan lazyMan;
private LazyMan() {
System.out.println(Thread.currentThread().getName());
}
public static LazyMan getInstance() {
//双重检查
if (null == lazyMan)
synchronized (LazyMan.class) {
if (null == lazyMan) lazyMan = new LazyMan();
}
return lazyMan;
}
}
5.静态内部类(推荐使用)
public class SingleTon {
private SingleTon() {}
//静态内部类(在类加载的时候不会立即实例化,调用getSingleTon时才会加载Inner类,从而完成SingleTon的实例化)
private static class Inner {
private static final SingleTon SINGLE_TON = new SingleTon();
}
public static SingleTon getSingleTon() {
return Inner.SINGLE_TON;
}
}
6.枚举式(推荐使用)
public enum SingleEnum {
INSTANCE;
public String getStr() {
return "hello singleEnum";
}
}
借助JDK1.5中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而
且还能防止反序列化重新创建新的对象。