我们在生活中见到的任务管理器就是单例模式,我们只能打开一个,打开多的也没有必要。
目录
定义:
- 某个类只有一个实例
- 必须自行创建这个实例
- 必须自行向整个系统提供这个实例
单例模式是一个对象型创建模式。
UML图:
单例模式我们怎么实现?
1:静态私有的成员变量
2:私有的构造方法
3:静态公有的方法来返回我们唯一实例
代码:
public class Singleton {
private static Singleton instance=null; //静态私有成员变量
//私有构造函数
private Singleton() {
}
//静态公有工厂方法,返回唯一实例
public static Singleton getInstance() {
if(instance==null)
instance=new Singleton();
return instance;
}
}
单例模式类型:
饿汉式单例
懒汉式单例
双重检查锁
静态内部类
饿汉式单例:
不加以判断,一上来就new出来。在多线程中存在多个实例问题。
public class EagerSingleton {
private static final EagerSingleton instance = new EagerSingleton();
private EagerSingleton() { }
public static EagerSingleton getInstance() {
return instance;
}
}
懒汉式:
这个也存在多线程问题:
我们加双重检测锁进行判断:来避免多线程中多个实例的问题:
public class LazySingleton {
private volatile static LazySingleton instance = null;
private LazySingleton() { }
public static LazySingleton getInstance() {
//第一重判断
if (instance == null) {
//锁定代码块
synchronized (LazySingleton.class) {
//第二重判断
if (instance == null) {
instance = new LazySingleton(); //创建单例实例
}
}
}
return instance;
}
}
静态内部类:
public class Singleton {
private Singleton() {
}
//静态内部类
private static class HolderClass {
private final static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return HolderClass.instance;
}
}