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

文章目录

单例模式

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

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

实现方式原理

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

● 私有化静态常量对象

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

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

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

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

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

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

相关推荐
Zane199419 小时前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫2 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19942 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19943 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..3 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1503 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)4 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki5 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅665 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa5 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio