一、单例模式
1.1 饿汉式
- 无须考虑多个线程同时访问的问题;调用速度和反应时间优于懒汉式单例;
- 资源利用效率不及懒汉式单例;
- 系统加载时间可能会比较长。
public class EagerSingleton {
private static EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {
}
public static EagerSingleton getInstance() {
return instance;
}
}
1.2 懒汉式
1.2.1 多线程不安全
package design.singleton;
public class LazySingleton {
private static LazySingleton instance = null;
int count;
private LazySingleton() {
count = 0;
}
public void add() {
++count;
}
public int count() {
return count;
}
public static LazySingleton getInstance() {
if(instance==null) {
instance = new LazySingleton();
}
return instance;
}
}
1.2.2 同步锁:锁方法
public class LazySingletonLock1 {
private static LazySingletonLock1 instance = null;
private LazySingletonLock1() {
}
public static synchronized LazySingletonLock1 getInstance() {
if(instance==null) {
instance = new LazySingletonLock1();
}
return instance;
}
}
1.2.3 同步锁:锁代码段
public class LazySingletonLock2 {
private static LazySingletonLock2 instance = null;
private LazySingletonLock2() {
}
public static LazySingletonLock2 getInstance() {
if(instance==null) {
synchronized(LazySingletonLock2.class) {
instance = new LazySingletonLock2();
}
}
return instance;
}
}
1.2.4 双重检查锁
public class LazySingletonDoubleCheckLock {
private volatile static LazySingletonDoubleCheckLock instance = null;
private LazySingletonDoubleCheckLock() {
}
public static LazySingletonDoubleCheckLock getInstance() {
if(instance==null) {
synchronized(LazySingletonDoubleCheckLock.class) {
if(instance==null) {
instance = new LazySingletonDoubleCheckLock();
}
}
}
return instance;
}
}
1.3 基于静态内部类
public class Singleton3 {
public static class SingletonHolder{
private static Singleton3 instance = new Singleton3();
}
private Singleton3() {
}
public static Singleton3 getInstance() {
return SingletonHolder.instance;
}
}