单例模式(五种创建方式)

文章目录

单例模式

属于创建型的设计模式,保证使用的对象只需要创建一次,重复使用一个对象,确保资源的重复使用,

使用场景:获取配置信息类,日志记录器、资源管理器(线程池资源、连接池资源)

实现方式原理

● 私有化的构造方法(防止外界访问)

● 私有化静态常量对象

● 公有化静态方法(获取对象方法 GetInstance)

饿汉式

在类加载时同时创建实例。

优点:不会出现线程不安全的问题

缺点:没有懒加载、出现资源浪费

实现方式:

java 复制代码
public class Instance{
    
	private static final Instance instance = new Instance();

    private Instance(){};

    public static Instance getInstance(){
    	return instance;
    }
}

枚举类

枚举类实现单例模式也是属于饿汉式的一种

java 复制代码
public enum InstanceExmple{

    INSTANCE;

    public void doSomeing(){
    	//进行添加其他成员变量的方法
    }
}

枚举实现是一种比较常用的方式。有着许多的优点。

线程安全且不会被反射破坏、枚举具有序列化与反序列化,在网络传输的过程中保持对象的一致性。

懒汉式

懒汉式:在使用时才加载对象,实现懒加载,资源利用。但是有可能会出现线程不安全的情况,可以使用加锁sychronized、双重检查、静态内部类等方式来解决。

普通方式

java 复制代码
public class Instance{

	private Static Instance instance;

    private Instance(){
        
    }

    public static Instance getInstance(){

        if(instance == null){
            instance = new Instance();
        }
        return instance;
    }
    
}

存在线程不安全的问题。

sychronized加锁

java 复制代码
public class Instance{

	private Static Instance instance;

    private Instance(){
        
    }

    public sychronized static Instance getInstance(){

        if(instance == null){
            instance = new Instance();
        }
        return instance;
    }
    
}

虽然实现了线程安全,但是效率性能较慢。

双重检查锁

java 复制代码
public class Instance{

	private volatile Static Instance instance;

    private Instance(){
        
    }

    public  static Instance getInstance(){

        if(instance == null){
            sychronize(Instance.class){
                if(instance == null){
                    instance = new Instance(); 
                }
            }
        }
        return instance;
    }
}

使用双重检查锁(Double check LockIng)实现,关键是volatile关键词,起到可见性和防止重排序的作用。

防止在判断对象是否为空时,因为重排序的原因导致误判,而继续创建对象。

这种实现方式解决了性能慢,线程安全。但是实现逻辑复杂。

静态内部类

java 复制代码
public class Instance{

    private Instance(){
        
    }

    private  static class InnerInstance{
        private static final Instance INSTANCE = new Instance();
    }

    public static Instance getInstance(){
        return InnerInstance.INSTANCE;
    }
}

推荐的一种方法,实现起来简单。是懒汉式的一种,可以在使用时才加载,而且不会被反射破坏。

实现起来较简单,定义私有构造,定义内部类、在内部类中创建静态常量的内部类。对外定义一个共有获取对象的接口。

以上代码均是在笔记本手敲、不保证完成正确、

总结起来,如果我们使用单例模式,要么使用静态内部类、要么就是枚举类。当然具体的使用方法还是根据实际情况。

写作不易,有用点个赞就行,谢谢~~~

相关推荐
咖啡八杯12 小时前
GoF设计模式——中介者模式
java·后端·spring·设计模式
胡萝卜术1 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
亦暖筑序2 天前
Java 8老系统Browser Agent实战:三层拦截把AI操作后台变成可审计流程
java·后端·设计模式
青禾网络4 天前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO5 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯5 天前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术6 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
艺艺生辉6 天前
迭代器模式-"我也想被增强for循环"
设计模式
咖啡八杯8 天前
GoF设计模式——策略模式
java·后端·spring·设计模式