单例模式简介

  • 模式属于创建型模式,它提供了一种创建对象的最佳方式。
  • 这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。
  • 这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
  • 主要分为:饿汉模式懒汉模式

饿汉模式

1
2
3
4
5
6
7
8
9
10
11
12
//饿汉模式
public class Hungry {
private static Hungry hungry = new Hungry();

private Hungry() {

}

public static Hungry getInstance() {
return hungry;
}
}

懒汉模式(单线程)

1
2
3
4
5
6
7
8
9
10
11
12
13
public class LazyMan01 {
private static LazyMan01 lazyMan;

private LazyMan01() {
}

public static LazyMan01 getInstance() {
if (lazyMan == null) {
lazyMan = new LazyMan01();
}
return lazyMan;
}
}

懒汉模式(多线程)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class LazyMan02 {
private volatile static LazyMan02 lazyMan;

private LazyMan02() {
}

//双重检测锁 懒汉单例模式 DCL懒汉模式
public static LazyMan02 getInstance() {
if (lazyMan == null) {
synchronized (LazyMan02.class) {
if (lazyMan == null) {
lazyMan = new LazyMan02();
}
}
}
return lazyMan;
}
}