成神之路的博客 成神之路的博客
首页
Java进阶
常用框架
架构设计
AI探索
Python
大数据
工具资源
关于博主
GitHub (opens new window)
首页
Java进阶
常用框架
架构设计
AI探索
Python
大数据
工具资源
关于博主
GitHub (opens new window)
  • 设计模式

    • 单例模式
      • 单例模式的实现方式
        • 1. 懒汉式,线程不安全
        • 2. 懒汉式,线程安全
        • 3. 饿汉式
        • 4. 双检锁/双重校验锁
        • 5. 登记式/静态内部类
        • 6. 枚举
  • 集合

  • 并发编程

  • 性能优化

  • Java
  • 设计模式
starxu
2024-03-11
目录

单例模式

# 单例模式

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

# 单例模式的实现方式

# 1. 懒汉式,线程不安全

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

# 2. 懒汉式,线程安全

public class Singleton {
    private static Singleton instance;
    private Singleton() {}
    
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
1
2
3
4
5
6
7
8
9
10
11

# 3. 饿汉式

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

# 4. 双检锁/双重校验锁

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

# 5. 登记式/静态内部类

public class Singleton {
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    private Singleton() {}
    
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
1
2
3
4
5
6
7
8
9
10

# 6. 枚举

public enum Singleton {
    INSTANCE;
    
    public void doSomething() {
        // 业务方法
    }
}
1
2
3
4
5
6
7
上次更新: 2025/07/01, 01:17:09
ArrayList源码分析

ArrayList源码分析→

最近更新
01
SpringCloud微服务实战
12-10
02
Java并发编程实战
11-05
03
JVM性能调优实战
10-15
更多文章>
Theme by Vdoing | Copyright © 2023-2025 star Xu | MIT License | xxxxx号 | xxxxxx
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式