单例设计模式
保证一个类只有一个实例,并提供一个全局的访问点,在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例
实现条件:
1.static sIntance
2.private SingleInstance(){}
3.static外部访问点
实现单例的两种方式:
懒汉式:实现对象的延迟加载,有3中实现方式
1.双重锁判断,保证线程安全
public class SingleInstance {
private static SingleInstance sIntance = null;
private SingleInstance() {}
public static SingleInstance getInstance() {
if (sIntance == null) {
Synchronized (Object.class) {
if (sIntance == null) {
sIntance = new SingleInstance();
}
}
}
return sIntance;
}
}
2.同步方法
public static SingleInstance getInstance() {
if (single == null) {
sIntance = new SingleInstance ();
}
return sIntance;
}
3.静态内部类(最优:安全,性能)
public class SingleInstance {
private SingleInstance() {};
private static class LazyClass {
privata static SingleInstance sIntance = new SingleInstance();
}
public static final SingleInstance getInstance() {
return LazyClass.sIntance ;
}
}
饿汉式:
public class SingleInstance {
private static SingleInstance sIntance = new SingleInstance();
private SingleInstance() {};
public static SingleInstance getInstance() {
return sIntance;
}
}