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

文章目录

单例模式

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

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

实现方式原理

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

● 私有化静态常量对象

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

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

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

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

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

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

相关推荐
会员果汁37 分钟前
14.设计模式-备忘录模式
设计模式·备忘录模式
xiaolyuh12311 小时前
Spring 框架 核心架构设计 深度详解
spring·设计模式·spring 设计模式
GISer_Jing21 小时前
智能体工具使用、规划模式
人工智能·设计模式·prompt·aigc
GISer_Jing1 天前
AI Agent:学习与适应、模型上下文协议
人工智能·学习·设计模式·aigc
小马爱打代码1 天前
MyBatis设计模式:构建者、工厂、代理模式
设计模式·mybatis·代理模式
月明长歌1 天前
Javasynchronized 原理拆解:锁升级链路 + JVM 优化 + CAS 与 ABA 问题(完整整合版)
java·开发语言·jvm·安全·设计模式
会员果汁1 天前
12.设计模式-状态模式
设计模式·状态模式
Yu_Lijing1 天前
基于C++的《Head First设计模式》笔记——抽象工厂模式
c++·笔记·设计模式
会员果汁1 天前
13.设计模式-适配器模式
设计模式·适配器模式
GISer_Jing2 天前
AI:多智能体协作与记忆管理
人工智能·设计模式·aigc