设计模式是前辈们在多年开发工作中经验的总结,可以提高代码的可重用性、可靠性和规范性,让代码更容易理解,而单例模式是在 Java 中最重要、最简单、最常用的设计模式之一。
应用场合:有些对象只需要一个就足够了,如古代皇帝,老婆
作用:保证整个应用程序中某个实例有且只有一个
单例模式有八种方式:
1. 饿汉式(静态常量)
2. 饿汉式(静态代码块)
3. 懒汉式(线程不安全)
4. 懒汉式(线程安全,同步方法)
5. 懒汉式(线程安全,同步代码块)
6. 双重检查
7. 静态内部类
8. 枚举
/**
* 饿汉式(静态常量)
*/
public class Singleton {
// 1.将构造方法私有化,不允许外部直接创建对象
private Singleton() {
}
// 2.创建类的唯一实例
private static Singleton instance = new Singleton();
// 3.提供一个用于获取实例的方法
public static Singleton getInstance() {
return instance;
}
}
/**
* 饿汉式(静态代码块)
*
* @author linan
*
*/
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
懒汉模式优缺点说明
1.起到了 lazy loading 的效果,但是只能在单线程下使用
2.如果在多线程下,一个线程进入了 if(instance == null) 判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例,所以在多线程环境下不可以使用这种方式
3.结论:在实际开发中不要使用这种方式
/**
* 懒汉式(线程不安全)
* 区别:饿汉模式的特点是加载类时比较慢,但运行时获取对象速度比较快
* 懒汉模式的特点是加载时比较快,但运行时获取对象速度比较快
*/
public class Singleton {
// 1.将构造方法私有化,不允许外部直接创建对象
private Singleton() {
}
// 2.声明类的唯一实例,使用 private static 修饰
private static Singleton instance;
// 3.提供一个用于获取实例的方法,使用 public static 修饰
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
/**
* 懒汉式(线程安全,同步方法)
*
* @author linan
*
*/
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
/**
* 懒汉式(线程安全,同步代码块)
*
* @author linan
*
*/
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
instance = new Singleton();
}
}
return instance;
}
}
双重检查优缺点说明
1.Double-Check 概念是多线程开发中常使用到的,如代码中所示,我们进行两次 if(instance == null) 检查,这样就可以保证线程安全了
2.这样,实例化代码只用执行一次,后面再次访问时,判断 if(instance == null),直接 return 实例化对象,也避免反复进行方法同步
3.线程安全:延迟加载;效率极高
4.结论:在实际开发中,推荐使用这种单例设计模式
/**
* 双重检查
*/
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
静态内部类优缺点说明
1.这种方式采用了类装载的机制来保证初始化实例时只有一个线程
2.静态内部类方式在 Singleton 类被转载时并不会立即实例化,而是在需要实例化时,调用 getInstance 方法,才会装载 SingletonInstance 类,从而完成 Singleton
的实例化
3.类的静态属性只会在第一次加载类的时候初始化,所以在这里,JVM 帮助我们保证了线程的安全性,在类进行初始化时,别的线程是无法进入的
4.优点:避免线程不安全,利用静态内部类特点来实现延迟加载,效率高
5.结论:推荐使用
/**
* 静态内部类
*
* @author linan
*
*/
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
/**
* 枚举
*
* @author linan
*
*/
public enum Singleton {
INSTANCE;
public void method() {
}
}