设计模式之单例模式
设计模式 Java juc 大约 1799 字作用
保证一个类只有一个实例,并提供一个访问它的全局访问点。
饿汉式(静态变量)
- 线程安全
- 未达到懒加载效果,可能造成内存浪费
- @see java.lang.Runtime
public class Singleton1 {
//1. 私有化构造函数,保证外部不能直接new
private Singleton1() {
}
//2. 类内部创建对象实例
private static final Singleton1 instance = new Singleton1();
//3. 提供公有静态方法,返回实例对象
public static Singleton1 getInstance() {
return instance;
}
}
饿汉式(静态代码块)
- 与饿汉式-静态变量效果一样
public class Singleton2 {
private Singleton2() {
}
private static Singleton2 instance;
static {
instance = new Singleton2();
}
public static Singleton2 getInstance() {
return instance;
}
}
懒汉式(同步方法)
- 懒加载、线程安全
- 获取实例时同步,效率降低
public class Singleton3 {
private Singleton3() {
}
private static Singleton3 instance;
//同步代码
public static synchronized Singleton3 getInstance() {
if (instance == null) {
instance = new Singleton3();
}
return instance;
}
}
双重检查
- 懒加载、线程安全
- 效率高
- 推荐使用
public class Singleton4 {
//防止在new对象时指令重排序
private static volatile Singleton4 instance;
private Singleton4() {
}
public static Singleton4 getInstance() {
if (instance == null) {
synchronized (Singleton4.class) {
if (instance == null) {
instance = new Singleton4();
}
}
}
return instance;
}
}
静态内部类
- 懒加载、线程安全
- 当Singleton5加载时,其静态内部类是不会被加载的,只有在调用getInstance()时才加载
- JVM类的装载机制保证线程安全
- 推荐使用
public class Singleton5 {
private Singleton5() {
}
private static class SingleInstance {
private static final Singleton5 INSTANCE = new Singleton5();
}
public static Singleton5 getInstance() {
return SingleInstance.INSTANCE;
}
}
枚举
- 推荐使用
enum Singleton6 {
INSTANCE
}
阅读 2339 · 发布于 2019-12-11
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Linux -bash: locate: command not found阅读 998
-
PostgreSQL 修改字段属性阅读 2526
-
Vue provide inject 组件传值阅读 442
-
GoLand 提示 Receiver has generic name阅读 2343
-
Vue 脚手架工具 Vue CLI阅读 423
-
SQL 注入和 XSS 攻击阅读 2664
-
macOS IDEA 显示 .DS_Store 文件阅读 392
-
Java 判断后缀是否匹配规则阅读 1856
-
skaffold init 提示 one or more valid Kubernetes manifests are required to run skaffold阅读 933
-
JVM:类的加载过程阅读 662