单例模式

单例模式

1、实现单例模式的条件

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

2、单例模式的优缺点

优点:

  • 1、在内存里只有一个实例,减少了内存的开销,尤其是频繁的创建和销毁实例(比网站页面缓存)。
  • 2、避免对资源的多重占用(比如写文件操作)。

缺点:
没有接口,不能继承,与单一职责原则冲突,一个类应该只关心内部逻辑,而不关心外面怎么样来实例化。

3、编写一个饿汉式

  • 线程安全、但是耗内存、相当于是用空间来换时间
package Single.com.cn;

/**
 * @Author Lin_Home
 * @Date 2020/11/8 15:13
 * @Version 1.0
 */

/*首先是饿汉式*/
public class HungerSingle {
    private final static HungerSingle single = new HungerSingle();
    private HungerSingle(){
        System.out.println(Thread.currentThread().getName());
    }

    public static HungerSingle getInstance(){
        return  single ;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
               HungerSingle.getInstance();
            });
        }
    }
}

4、编写一个懒汉式

package Single.com.cn;

/**
 * @Author Lin_Home
 * @Date 2020/11/9 8:44
 * @Version 1.0
 */

/*懒汉式*/
public class LazySingle {
    private  static LazySingle lazySingle;
    private LazySingle() {
        System.out.println(Thread.currentThread().getName());
    }

    public static LazySingle getLazySingle(){
            if (lazySingle == null){
                lazySingle = new LazySingle();
            }
            return lazySingle;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{ LazySingle.getLazySingle();}).start();
        }
    }
}

  • 通过运行上面的代码找到,线程是不安全的,那么线程不安全怎么处理?

使用双检锁/双重校验锁(DCL,即 double-checked locking)

package Single.com.cn;

/**
 * @Author Lin_Home
 * @Date 2020/11/9 8:44
 * @Version 1.0
 */

/*懒汉式*/
public class LazySingle {
    private volatile static LazySingle lazySingle;

    private LazySingle() {
        System.out.println(Thread.currentThread().getName());
    }

    public static LazySingle getLazySingle(){
        if (lazySingle == null){
            synchronized (LazySingle.class){
                if (lazySingle == null){
                    lazySingle = new LazySingle(); //注意 当这个实例没有使用修饰成原子的时候,会存在指令重排的问题,也就是存在构造器没有完成,就进行调用
                }
            }
        }
        return lazySingle;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{ LazySingle.getLazySingle();}).start();
        }
    }
}

注意,来一个问题,懒汉式一定能保证线程安全吗?

  • 当通过反射方法实现,可以修改私有方法
package Single.com.cn;

import java.lang.reflect.Constructor;

/**
 * @Author Lin_Home
 * @Date 2020/11/9 8:44
 * @Version 1.0
 */

/*懒汉式*/
public class LazySingle {
    private volatile static LazySingle lazySingle;

    private LazySingle() {
    }

    public static LazySingle getLazySingle(){
        if (lazySingle == null){
            synchronized (LazySingle.class){
                if (lazySingle == null){
                    lazySingle = new LazySingle();
                }
            }
        }
        return lazySingle;
    }

    public static void main(String[] args) throws Exception {
        LazySingle lazySingle = LazySingle.getLazySingle();

        Class<LazySingle> aClass = LazySingle.class;
        Constructor<LazySingle> constructor = aClass.getDeclaredConstructor(null);
        //反射能修改private的属性值
        constructor.setAccessible(true);
        LazySingle lazySingle1 = constructor.newInstance();
        System.out.println(lazySingle.hashCode());
        System.out.println(lazySingle1.hashCode());
    }


}

  • 打印出来的hashcode 值
    在这里插入图片描述

  • 那么防止在生成一个实例化对象,我继续改进,在初始化构造器的,进行第三次检测

 private LazySingle() {
        if (lazySingle != null){
            throw new RuntimeException("不可使用反射进行破坏");
        }
    }
  • 假如我全部都是通过反射实例化,实例化出来的对象还是实现二次赋值
package Single.com.cn;

import java.lang.reflect.Constructor;

/**
 * @Author Lin_Home
 * @Date 2020/11/9 8:44
 * @Version 1.0
 */

/*懒汉式*/
public class LazySingle {
    private volatile static LazySingle lazySingle;

    private LazySingle() {
        if (lazySingle != null){
            throw new RuntimeException("不可使用反射进行破坏");
        }
    }

    public static LazySingle getLazySingle(){
        if (lazySingle == null){
            synchronized (LazySingle.class){
                if (lazySingle == null){
                    lazySingle = new LazySingle();
                }
            }
        }
        return lazySingle;
    }

    public static void main(String[] args) throws Exception {
   

//        LazySingle lazySingle = LazySingle.getLazySingle();

        Class<LazySingle> aClass = LazySingle.class;
        Constructor<LazySingle> constructor = aClass.getDeclaredConstructor(null);
        //反射能修改private的属性值
        constructor.setAccessible(true);
        LazySingle lazySingle1 = constructor.newInstance();
        LazySingle lazySingle = constructor.newInstance();
        System.out.println(lazySingle.hashCode());
        System.out.println(lazySingle1.hashCode());
    }

}

  • 继续,我在初始化的时候,加上一个标识符进行判断,是不是还是原来的那个方法
package Single.com.cn;

import java.lang.reflect.Constructor;

/**
 * @Author Lin_Home
 * @Date 2020/11/9 8:44
 * @Version 1.0
 */

/*懒汉式*/
public class LazySingle {
    private volatile static LazySingle lazySingle;
    public static  boolean flag = false;

    private LazySingle() {
        if (flag == false){
            flag = true;
        }else {
            throw new RuntimeException("不可使用反射进行破坏");
        }
    }

    public static LazySingle getLazySingle(){
        if (lazySingle == null){
            synchronized (LazySingle.class){
                if (lazySingle == null){
                    lazySingle = new LazySingle();
                }
            }
        }
        return lazySingle;
    }

    public static void main(String[] args) throws Exception {
        Class<LazySingle> aClass = LazySingle.class;
        Constructor<LazySingle> constructor = aClass.getDeclaredConstructor(null);
        //反射能修改private的属性值
        constructor.setAccessible(true);
        LazySingle lazySingle1 = constructor.newInstance();
        LazySingle lazySingle = constructor.newInstance();
        System.out.println(lazySingle.hashCode());
        System.out.println(lazySingle1.hashCode());
    }
}

在这里插入图片描述

  • 果然这个是可行的,但是如果这个属性对应的属性变量是什么的,又可以产生危害
package Single.com.cn;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * @Author Lin_Home
 * @Date 2020/11/9 8:44
 * @Version 1.0
 */

/*懒汉式*/
public class LazySingle {
    private volatile static LazySingle lazySingle;
    private static  boolean flag = false;

    private LazySingle() {
        if (flag == false){
            flag = true;
        }else {
            throw new RuntimeException("不可使用反射进行破坏");
        }
    }

    public static LazySingle getLazySingle(){
        if (lazySingle == null){
            synchronized (LazySingle.class){
                if (lazySingle == null){
                    lazySingle = new LazySingle();
                }
            }
        }
        return lazySingle;
    }

    public static void main(String[] args) throws Exception {
        Class<LazySingle> aClass = LazySingle.class;
        Constructor<LazySingle> constructor = aClass.getDeclaredConstructor(null);

        Field field = aClass.getDeclaredField("flag");
        field.setAccessible(true);

        //反射能修改private的属性值
        constructor.setAccessible(true);

        LazySingle lazySingle = constructor.newInstance();
        field.set(lazySingle,false);

        LazySingle lazySingle1 = constructor.newInstance();


        System.out.println(lazySingle.hashCode());
        System.out.println(lazySingle1.hashCode());
    }


}

  • 得出的结果还是可以改变单例

在这里插入图片描述

5、枚举实现单例

package Single.com.cn;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author Lin_Home
 * @Date 2020/11/9 15:18
 * @Version 1.0
 */
public enum  EnumDemo {
    INSTANCE;

    public EnumDemo getInstance(){
        return INSTANCE;
    }
}

class Test{
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        EnumDemo enumDemo = EnumDemo.INSTANCE;
        Constructor<EnumDemo> declaredConstructor = EnumDemo.class.getDeclaredConstructor(String.class, int.class);
        declaredConstructor.setAccessible(true);

        EnumDemo enumDemo1 = declaredConstructor.newInstance();
        System.out.println(enumDemo.hashCode());
        System.out.println(enumDemo1.hashCode());
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值