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

文章目录

单例模式

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

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

实现方式原理

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

● 私有化静态常量对象

● 公有化静态方法(获取对象方法 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;
    }
}

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

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

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

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

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

相关推荐
Mh4 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊5 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式
dahaihua3336 天前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
wy_hhxx7 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥7 天前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
用户624293196627 天前
告别 Electron 臃肿与 Wireshark 老化界面:用 Rust + Tauri 2.0 构建多总线网络与现场总线深度分析仪 Omni-Probe
设计模式
是2的10次方啊8 天前
设计模式与生活㉒:暖气热不热,得一间一间摸过去
设计模式
bigbread8 天前
迭代器模式-在区域健康档案导出中的实战应用
设计模式
装不满的克莱因瓶8 天前
设计模式之策略模式核心概念和应用场景
java·后端·设计模式·架构·系统架构·策略模式
是2的10次方啊8 天前
设计模式与生活㉑:一句“建议复查”,是好几句话拼出来的
设计模式