java设计模式-单例模式

单例模式

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

注意:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。

应用实例:
1、一个班级只有一个班主任。
2、Windows 是多进程多线程的,在操作一个文件的时候,就不可避免地出现多个进程或线程同时操作一个文件的现象,所以所有文件的处理必须通过唯一的实例来进行。
3、一些设备管理器常常设计为单例模式,比如一个电脑有两台打印机,在输出的时候就要处理不能两台打印机打印同一个文件。

实现:
饿汉单例模式
当类获取对象的时候,无论你是否需要该对象,都会创建该单例对象,就像一个饿汉急切的需要食物一样。

代码实现

懒汉式,线程不安全

//饿汉单例模式
public class SingleTon {
    //1、必须私有构造器:私有构造器对外不能被访问。
    private SingleTon() {
    }
    //2、static修饰的成员变量,静态成员变量,加载一次,只有一份
    private static final SingleTon INSTANCE=new SingleTon();
    public static SingleTon getInstance(){
        return INSTANCE;
    }
}

1、必须私有构造器:私有构造器对外不能被访问。
2、static修饰的成员变量,静态成员变量,加载一次,只有一份
3、由于构造器私有了,所以外面不能创建该类的实例对象。该类的实例对象只能通过初始化语句

private static final SingleTon INSTANCE=new SingleTon();

创建,因此实现了单例模式
4、该方式基于 classloader 机制避免了多线程的同步问题,不过,instance 在类装载时就实例化,虽然导致类装载的原因有很多种,在单例模式中大多数都是调用 getInstance 方法, 但是也不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化 instance 显然没有达到 lazy loading 的效果。

懒汉单例模式
在真正需要对象的时候才去创建对象(延迟加载对象)

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
  
    public static Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  
}

当需要Singleton对象的时候调用getInstance()方法创建对象
这种实现最大的问题就是不支持多线程。因为没有加锁 synchronized,所以严格意义上它并不算单例模式。
这种方式 lazy loading 很明显,不要求线程安全,在多线程不能正常工作。

public class Singleton {
    private static Singleton instance;
    private Singleton (){
        System.out.println("init");
    }
    public static Singleton getInstance() {
        if (instance == null){
            instance = new Singleton();
        }
        return instance;
    }

    public static void main(String[] args) {
        Thread[] threads=new Thread[100];
        for (int i = 0; i < threads.length; i++) {
            threads[i]=new Thread(()->{
                Singleton.getInstance();
            });
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
    }
}

运行结果
在这里插入图片描述
可见这种单例模式并不能真正实现单例
多个线程可能同时运行到下面的if判断语句,如果此时没有单例对象,那instance == null成立
这样就会创建多个对象

if (instance == null){
   instance = new Singleton();
}

懒汉式,线程安全

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
    public static synchronized Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  
}

但是该方法将锁加在了方法上,每有一个线程执行该方法都会加锁,这导致后面的方法执行该方法时都要进行等待。当对象创建完成后,后面的线程执行该方法时仍然会加锁,解锁。这样在这个方法上浪费了大量的时间。

双检锁/双重校验锁

public class Singleton2 {
    private static Singleton2 instance;
    private Singleton2 (){
        System.out.println("init");
    }
    public static Singleton2 getInstance() {
        if (instance == null) {//一旦有线程创建了实例,直接return,提高效率。如果instance == null成立说明没创建实例,进入创建实例的语句。
            synchronized (Singleton2.class){
                if (instance == null){//防止同时创建多个线程
                    instance = new Singleton2();
                }
            }
        }
        return instance;
    }
}

该方式将锁加在了创建实例的代码块
这样如果以前的线程创建了实例,新的线程就直接因为不满足instance == null的条件直接返回return instance了。这样相比上面的方式大大提高了效率。

反射破解单例模式
使用反射破解单例模式,建立多个对象

public class Singleton2 {
    private static Singleton2 instance;
    private Singleton2 (){
        System.out.println("init");
    }
    public static Singleton2 getInstance() {
        if (instance == null) {
            synchronized (Singleton2.class){
                if (instance == null){
                    instance = new Singleton2();
                }
            }
        }
        System.out.println();
        return instance;
    }
    public static void main(String[] args) throws Exception {
        Class single=Class.forName("com.company.Singleton2");
        Constructor m=single.getDeclaredConstructor();
        m.setAccessible(true);
        m.newInstance();
        m.newInstance();
        m.newInstance();
        m.newInstance();
    }
}

在这里插入图片描述
可见创建了多个对象

防止反射破解
在Construct类中的newInstance方法中有一个判断条件
if ((this.clazz.getModifiers() & 16384) != 0) {
throw new IllegalArgumentException(“Cannot reflectively create enum objects”);
}
如果是枚举类型,就会抛出异常,因此只有枚举才能避免被反射破坏
反射在通过newInstance创建对象时,会检查该类是否ENUM修饰,如果是则抛出异常,反射失败。

public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        if (!this.override) {
            Class<?> caller = Reflection.getCallerClass();
            this.checkAccess(caller, this.clazz, this.clazz, this.modifiers);
        }

        if ((this.clazz.getModifiers() & 16384) != 0) {
            throw new IllegalArgumentException("Cannot reflectively create enum objects");
        } else {
            ConstructorAccessor ca = this.constructorAccessor;
            if (ca == null) {
                ca = this.acquireConstructorAccessor();
            }

            T inst = ca.newInstance(initargs);
            return inst;
        }
    }

所以通过枚举的形式实现单例能够防止反射创建多个实例

public enum Etp {
    INSTANCE;

    public Etp getInstance(){
        return INSTANCE;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值