目录
简介
一个类只允许创建一个对象(或者实例),那这个类就是一个单例类
实际应用场景
在一些常用的工具类、线程池、缓存,数据库,账户登录系统、配置文件等程序中可能只允许我们创建一个对象
UML
代码实现
1.饿汉式(线程安全) [不推荐用]
/**
* 饿汉式(线程安全) [不推荐用]
* <p>
* 不支持延迟加载
*
* @author xiaoy
* @since 2021-3-22 9:12
*/
class Single1 {
private static Single1 single1 = new Single1();
public static Single1 getInstance() {
return single1;
}
}
2.懒汉式(线程不安全) [不推荐用]
/**
* 懒汉式-无锁(线程不安全) [不推荐用]
* <p>
* 优势是支持延迟加载,需要线程安全的处理
*
* @author xiaoy
* @since 2021-3-22 9:16
*/
class Single2 {
private static Single2 single2 = null;
public static Single2 getInstance() {
if (single2 == null) {
single2 = new Single2();
}
return single2;
}
}
3.懒汉式-加锁(线程安全) [不推荐用]
/**
* 懒汉式(线程安全) [不推荐用]
* <p>
* 每次获得实例都要同步,开销很大,性能很低
*
* @author xiaoy
* @since 2021-3-22 9:16
*/
class Single21 {
private static Single21 single21 = null;
public synchronized static Single21 getInstance() {
if (single21 == null) {
single21 = new Single21();
}
return single21;
}
}
4.懒汉式-双重校验锁(线程安全) [推荐用]
/**
* 懒汉式-双重校验锁(线程安全) [推荐用]
* <p>
* instance 成员变量加了volatile 关键字修饰,是为了防止指令重排
*
* @author xiaoy
* @since 2021-3-22 9:16
*/
class Single3 {
private volatile static Single3 single3 = null;
public static Single3 getInstance() {
if (single3 == null) {
synchronized (Single3.class) {
if (single3 == null) {
single3 = new Single3();
}
}
}
return single3;
}
}
5.枚举(线程安全) [极推荐使用]
/**
* 枚举(线程安全) [极推荐使用]
* <p>
* 写法简洁,代码短小精悍,防止反序列化和反射的破坏
*
* @author xiaoy
* @since 2021-3-22 9:42
*/
enum Single4 {
INSTANCE;
public void show() {
}
}
6.静态内部类(线程安全) [推荐用]
/**
* 静态内部类(线程安全) [推荐用]
* <p>
* 优点:避免了线程不安全,延迟加载,效率高
*
* @author xiaoy
* @since 2021-3-22 9:42
*/
class Single5 {
private Single5() {
}
private static class SingleHolder {
private static Single5 single5 = new Single5();
}
public static Single5 getInstance() {
return SingleHolder.single5;
}
}
7. 测试代码
/**
* 测试
*
* @author xiaoy
* @since 2021-3-22 9:49
*/
public class Main {
public static void main(String[] args) {
System.out.println(Single1.getInstance());
System.out.println(Single1.getInstance());
System.out.println("***********");
System.out.println(Single2.getInstance());
System.out.println(Single2.getInstance());
System.out.println("***********");
System.out.println(Single21.getInstance());
System.out.println(Single21.getInstance());
System.out.println("***********");
System.out.println(Single3.getInstance());
System.out.println(Single3.getInstance());
System.out.println("***********");
System.out.println(Single4.INSTANCE);
System.out.println(Single4.INSTANCE);
System.out.println("***********");
System.out.println(Single5.getInstance());
System.out.println(Single5.getInstance());
}
}
测试
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15386.html