1、单例模式的好处:
使用Singleton的好处还在于可以节省内存,因为它限制了实例的个数,
有利于Java垃圾回收(garbage collection)。
2、单例模式的特征
构造函数私有化,不能产生对象,所以只能用类名调用,所有只能是静态函数。
3、代码编写
第一种(懒汉,线程不安全)
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
第二种(懒汉,线程安全):
public static synchronized Singleton getInstance() {
if (single == null) {
single = new Singleton();
}
return single;
}
遗憾的是,效率很低,99%情况下不需要同步,每次都会加锁
改进算法
public static Singleton getInstance() {
if (single == null) {
synchronized (single) {
single = new Singleton();
}
}
return single;
}
第三种(饿汉)
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
基于classloder机制避免了多线程的同步问题,不过,instance在类装载时就实例化,虽然导致类装载的原因有很多种,在单例模式中大多数都是调用getInstance方法, 但是也不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化instance显然没有达到lazy loading的效果
第四种(静态内部类)
public class Singleton {
private static class LazyHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
这种方式同样利用了classloder的机制来保证初始化instance时只有一个线程