单例模式

概述

单例模式,顾名思义就是在整个运行是域,一个类只有一个实例对象

为什么需要单例模式呢?

因为,有的类的实例对象的创建和销毁对资源来说消耗不大,

然而有的类比较庞大和复杂,如果平频繁的创建和销毁对象,并且这些对象完全是可以复用的话,那么将造成一些不必要的性能的浪费

比如:

现在需要访问数据库,创建数据库链接对象是一个耗资源的操作,并且数据库连接完全是可以复用的,那么就可以将这个对象设计成单例的,这样只需要创建依次并且重复使用这个对象就行了。

而不需要每次访问数据库都创建一个链接对象,如果那么做将是一个非常恐怖的事情

Java中的实现

实现单例模式,需要考虑三点

  1. 是否线程安全
  2. 是否懒加载
  3. 是否反射破坏

懒汉式,线程不安全

1
2
3
4
5
6
7
8
9
10
11
public class Singleton {  
private static Singleton instance;
private Singleton (){}

public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

特点

  • 懒加载
  • 多线程不安全

懒汉式,线程安全

1
2
3
4
5
6
7
8
9
10
11
public class Singleyton{
priavte static Singleton instance;
private Singleton (){}

public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

特点

  • 懒加载
  • 多线程安全
  • 每次getInstance()都要加锁,效率较低

饿汉式

1
2
3
4
5
6
7
public class Singleton {  
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}

特点

  • 不是懒加载
  • 多线程安全

双重检查锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Singleton {  
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}

特点

  • 懒加载
  • 多线程安全