单例模式
简介
定义:单例模式主要是为了避免因为创建了多个实例造成资源的浪费,且多个实例由于多次调用容易导致结果出现错误,而使用单例模式能够保证整个应用中有且只有一个实例。
使用场景:
配置管理器
日志管理器
数据库连接池
线程池
实现方式:
懒汉式(线程不安全)
懒汉式(线程安全,synchronized)
双重检查锁定
饿汉式
静态内部类
枚举(推荐)
UML
代码示例
需要创建单例的客户端
@Data
public class Client {
private String name;
}单例实现
public enum Single {
INSTANCE;
private Client client;
Single() {
this.client = new Client();
}
public Client getClient() {
return client;
}
}使用方式
public class Test {
public static void main(String[] args) {
Client client = Single.INSTANCE.getClient();
Client client1 = Single.INSTANCE.getClient();
System.out.println(client == client1);
}
}Last updated
Was this helpful?