一、单例模式介绍
单例模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法(静态方法)。
二、单例模式的实现方式
- 饿汉式(静态常量)
- 饿汉式(静态代码块)
- 懒汉式(线程不安全)
- 懒汉式(线程安全,同步方法)
- 懒汉式(线程不安全,同步代码块)
- 双重检查
- 静态内部类
- 枚举
三、单例模式实现示例
1.饿汉式(静态常量)
public class SingletonTypeOne {
private SingletonTypeOne() {
}
private static final SingletonTypeOne INSTANCE = new SingletonTypeOne();
public static SingletonTypeOne getInstance() {
return INSTANCE;
}
}
注意:线程安全但是浪费内存。 (不推荐)
2.饿汉式(静态代码块)
public class SingletonTypeTwo {
private static SingletonTypeTwo singletonTypeTwo;
static {
singletonTypeTwo = new SingletonTypeTwo();
}
private SingletonTypeTwo() {
}
public static SingletonTypeTwo getInstance() {
return singletonTypeTwo;
}
}
注意:线程安全但是浪费内存。(不推荐)
3.懒汉式(线程不安全)
public class SingletonTypeThree {
private static SingletonTypeThree singletonTypeThree;
private SingletonTypeThree() {
}
public static SingletonTypeThree getInstance() {
if (singletonTypeThree == null) {
singletonTypeThree = new SingletonTypeThree();
}
return singletonTypeThree;
}
}
注意:线程不安全。(不推荐)
4.懒汉式(线程安全,同步方法)
public class SingletonTypeFour {
private static SingletonTypeFour singletonTypeFour;
private SingletonTypeFour() {
}
public static synchronized SingletonTypeFour getInstance() {
if (singletonTypeFour == null) {
singletonTypeFour = new SingletonTypeFour();
}
return singletonTypeFour;
}
}
注意:线程安全,性能较差。(不推荐)
5.懒汉式(线程不安全,同步代码块)
public class SingletonTypeFive {
private static SingletonTypeFive singletonTypeFive;
private SingletonTypeFive() {
}
public static SingletonTypeFive getInstance() {
if (singletonTypeFive == null) {
synchronized (SingletonTypeFive.class) {
singletonTypeFive = new SingletonTypeFive();
}
}
return singletonTypeFive;
}
}
注意:线程不安全。(不推荐)
6.双重检查
public class SingletonTypeSix {
private static volatile SingletonTypeSix singletonTypeSix;
private SingletonTypeSix() {
}
public static SingletonTypeSix getInstance() {
if (singletonTypeSix == null) {
synchronized (SingletonTypeSix.class) {
if (singletonTypeSix == null) {
singletonTypeSix = new SingletonTypeSix();
}
}
}
return singletonTypeSix;
}
}
注意:线程安全。(推荐)
7.静态内部类
public class SingletonTypeSeven {
private SingletonTypeSeven() {
}
private static class SingletonTypeSevenInstance {
private static final SingletonTypeSeven SINGLETON_TYPE_SEVEN = new SingletonTypeSeven();
}
public static SingletonTypeSeven getInstance() {
return SingletonTypeSevenInstance.SINGLETON_TYPE_SEVEN;
}
}
注意:线程安全。(推荐)
8.枚举
public enum SingletonTypeEight {
INSTANCE;
public void method() {
//TODO
}
}
注意:线程安全。(推荐)
四、使用场景
1. jdk中的运用:java.lang.Runtime(饿汉模式)
2.需要频繁的进行创建和销毁对象、创建对象时耗时过多或耗费资源过多但是又要经常用到的对象、工具类对象、频繁的访问数据库或文件的对象(数据源,session工厂)。