设计模式:单例模式
定义
单例模式的定义:Ensure a class has only one instance, and provide a global point of access to it.(确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。)
结构类图
单例模式的通用类图:
单例类的实现通常注意三点:
单例类的构造函数为私有;
提供一个自身的静态私有成员变量;
提供一个公有的静态工厂方法。
下面来看看Java中单例模式的常见实现。
饿汉式
/*
* 饿汉式:线程安全,长期占用内存,效率较低
*/
public class Singleton1 {
private static final Singleton1 instance = new Singleton1();
private Singleton1() {
};
public static Singleton1 getInstance() {
return instance;
}
}
懒汉式
/*
* 懒汉式:线程安全,每次调用都会获取同步锁
*/
public class Singleton2 {
private static Singleton2 instance = null;
private Singleton2() {
};
public static Singleton2 getInstance() {
synchronized (Singleton2.class) {
if (instance == null) {
instance = new Singleton2();
}
}
return instance;
}
}
双重校验锁(DCL)
/*
* 双重校验锁(DCL)
*/
public class Singleton3 {
private static volatile Singleton3 instance = null;
private Singleton3() {
};
public static Singleton3 getInstance() {
if (instance == null) {
synchronized (Singleton3.class) {
if (instance == null) {
instance = new Singleton3();
}
}
}
return instance;
}
}
静态内部类
/*
* 静态内部类
*/
public class Singleton4 {
private static class SingletonHolder {
public static final Singleton4 instance = new Singleton4();
}
private Singleton4() {
};
public static Singleton4 getInstance() {
return SingletonHolder.instance;
}
}
枚举
/*
* 枚举
*/
public enum Singleton5 {
instance;
}
总结
- 单例模式的主要优点在于提供了对唯一实例的受控访问并可以节约系统资源;其主要缺点在于因为缺少抽象层而难以扩展,且单例类职责过重。
- 单例模式适用情况包括:系统只需要一个实例对象;客户调用类的单个实例只允许使用一个公共访问点。