单例模式

  1. 0x00 单例的几种实现方式:
  2. 0x01 饿汉式
  3. 0x02 懒汉式
  4. 0x03 静态内部类
  5. 0x04 枚举
  6. 0x05 双重校验锁

0x00 单例的几种实现方式:

  • 饿汉式
  • 懒汉式
  • 静态内部类
  • 枚举
  • 双重校验锁

类图:

classDiagram

class Singleton{
    +private Singleton()
    +private static final Singleton instance
    +public static Singleton getInstance()
}

Singleton<|-- Singleton

0x01 饿汉式

这是最简单的单例实现方式之一,它在类加载时就创建了单例对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Singleton {
// 私有构造函数,防止外部实例化
private Singleton() {}

// 唯一的实例
private static final Singleton instance = new Singleton();

// 获取唯一实例的方法
public static Singleton getInstance() {
return instance;
}
}

0x02 懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 方式一,  线程不安全. 在不强调性的情况下, 采用这种方式.
public class Singleton {
private Singleton() {}

private static Singleton instance;

public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
// 方式二, 线程安全.
public class Singleton {
private Singleton() {}

private static Singleton instance;

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

0x03 静态内部类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 这种方式结合了懒加载的优点,同时保持了线程安全性.
// 即 不调用时,不会创建实例, 在调用时, 会创建实例.
public class Singleton {
private Singleton() {}

private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}

0x04 枚举

1
2
3
4
5
6
7
8
// 使用枚举来实现单例是一种简单有效的方式,而且可以避免同步问题。
public enum Singleton {
INSTANCE;
public void someMethod() {
// 实现方法
}
}

0x05 双重校验锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 双重检查锁定是一种高效的懒汉式单例实现方式,它只在必要时同步代码块。
public class Singleton {
private Singleton() {}

private volatile static Singleton instance;

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

文章标题:单例模式

本文作者:zhu8fei

发布时间:2024-08-13, 15:51:57

最后更新:2024-08-15, 09:37:02

原始链接:http://www.zhu8fei.com/2024/08/13/singleton-pattern.html

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 zhu8fei@163.com

目录
×

喜欢就点赞,疼爱就打赏