单例模式

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

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

实现方式原理
● 私有化的构造方法(防止外界访问)
● 私有化静态常量对象
● 公有化静态方法(获取对象方法 GetInstance)

饿汉式

在类加载时同时创建实例。
优点:不会出现线程不安全的问题
缺点:没有懒加载、出现资源浪费

实现方式:

public class Instance{
    
	private static final Instance instance = new Instance();

    private Instance(){};

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

枚举类

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

public enum InstanceExmple{

    INSTANCE;

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

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

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

懒汉式

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

普通方式

public class Instance{

	private Static Instance instance;

    private Instance(){
        
    }

    public static Instance getInstance(){

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

存在线程不安全的问题。

sychronized加锁

public class Instance{

	private Static Instance instance;

    private Instance(){
        
    }

    public sychronized static Instance getInstance(){

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

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

双重检查锁

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关键词,起到可见性和防止重排序的作用。

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

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

静态内部类

public class Instance{

    private Instance(){
        
    }

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

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

推荐的一种方法,实现起来简单。是懒汉式的一种,可以在使用时才加载,而且不会被反射破坏。
实现起来较简单,定义私有构造,定义内部类、在内部类中创建静态常量的内部类。对外定义一个共有获取对象的接口。

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

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

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

01-28 03:02