设计模式--单例模式

设计模式–单例模式

1. 应用场景

需要频繁的进行创建和销毁的对象、创建对象时耗时过多或耗费资源过多(即:重量级对象),但又经常用到的对象、工具类对象、频繁访问数据库或文件的对象(比如数据源、session工厂等)

2. 常见的单例模式

2.1 饿汉式(静态常量)

public class SingleInstance {
    // 私有化构造方法
    private SingleInstance(){

    }
    // 私有化实例
    private static final SingleInstance singleInstance = new SingleInstance();

    // 对外提供实例访问方法
    public static SingleInstance getInstance(){
        return singleInstance;
    }
}

public class Client {
    public static void main(String[] args) {
        // 通过对外暴露的实例方法获取实例
        SingleInstance instance = SingleInstance.getInstance();
        SingleInstance instance1 = SingleInstance.getInstance();
        System.out.println(instance.hashCode()==instance1.hashCode());
    }
}
  • 优点:这种写法比较简单,就是在类装载的时候就完成实例化。
    避免了线程同步问题
  • 缺点:在类装载的时候就完成实例化,没有达到Lazy Loading的
    效果。如果从始至终从未使用过这个实例,则会造成内存的浪费

2.2 饿汉式(静态代码块)

public class SingleInstance {
    // 私有化构造方法
    private SingleInstance(){

    }
    // 私有化实例
    private static SingleInstance singleInstance;

    static{ //在静态代码块中创建实例
        singleInstance=new SingleInstance();
    }

    // 对外提供实例访问方法
    public static SingleInstance getInstance(){
        return singleInstance;
    }
}
  • 这种方式和上面的方式其实类似,只不过将类实例化的过程放在了静态代码块中,也是在类装载的时候,就执行静态代码块中的代码,初始化类的实例。优缺点和上面是一样的。

2.3懒汉式(线程不安全)

public class SingleInstance {
    // 私有化构造方法
    private SingleInstance(){
        
    }
    
    private static SingleInstance singleInstance;
    
    // 提供对外获取实例的方法
    public static SingleInstance getInstance(){
        // 存在线程安全问题
        if(singleInstance == null){
            singleInstance=new SingleInstance();
        }
        return singleInstance;
    }
    
    
}
  • 优点: 起到了Lazy Loading的效果,但是只能在单线程下使用
  • 如果在多线程下,一个线程进入了if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可使用这种方式

2.4 懒汉式(线程安全,同步方法)

public class SingleInstance {
    // 私有化构造方法
    private SingleInstance(){

    }

    private static SingleInstance singleInstance;

    // 提供对外获取实例的方法
    // 同步方法 效率较低
    public static synchronized SingleInstance getInstance(){
        // 存在线程安全问题
        if(singleInstance == null){
            singleInstance=new SingleInstance();
        }
        return singleInstance;
    }


}
  • 解决了线程不安全问题
  • 效率太低了,每个线程在想获得类的实例时候,执行getInstance()方法都要进行同步。而其实这个方法只执行一次实例化代码就够了,后面的想获得该类实例,直接return就行了。方法进行同步效率太低

2.5 懒汉式(同步代码块 双重校验机制)

public class SingleInstance {
    // 私有化构造方法
    private SingleInstance(){

    }

    private static SingleInstance singleInstance;

    // 提供对外获取实例的方法
    public static SingleInstance getInstance(){
        if(singleInstance == null){
            // 同步代码块
            synchronized (SingleInstance.class){
                // 再次校验 防止在多线程情况下 多个线程进入到该方法 出现线程不安全问题
                if(singleInstance == null){
                    singleInstance=new SingleInstance();
                }
            }
        }
        return singleInstance;
    }
}

2.6 静态内部类

public class SingleInstance {
    // 私有化构造方法
    private SingleInstance(){

    }

    //写一个静态内部类,该类中有一个静态属性 Singleton
    private static class SingletonInstance {
        private static final SingleInstance INSTANCE = new SingleInstance();
    }
    
    
    public static SingleInstance getInstance(){
        return SingletonInstance.INSTANCE;
    }
}
  • 这种方式采用了类装载的机制来保证初始化实例时只有一个线程。
  • 静态内部类方式在Singleton类被装载时并不会立即实例化,而是在需要实例化时,调用getInstance方法,才会装载SingletonInstance类,从而完成Singleton的实例化。
  • 类的静态属性只会在第一次加载类的时候初始化,所以在这里,JVM帮助我们保证了线程的安全性,在类进行初始化时,别的线程是无法进入的。

2.7 枚举

enum Singleton {
	INSTANCE;
	public void sayOK() {
		System.out.println("ok~");
	}
}

3 单例模式存在风险

public class Reflex {
    private Reflex(){
        }

        System.out.println(Thread.currentThread().getName()+"ok");
    }
    private volatile static Reflex Reflex;

    public static Reflex getInstance(){
        if (Reflex==null) {
            synchronized (Reflex.class){
                if (Reflex==null) {
                    Reflex=new Reflex();//不是一个原子性操作
                }
            }
        }
        return Reflex;
    }

    public static void main(String[] args) throws Exception {//异常抛到最大
        Reflex instance=Reflex.getInstance();//正常创建
        
        //反射破坏单例,获取反射对象,拿到构造器,空参所以null
        Constructor<Reflex> declaredConstructor = 		 	      Reflex.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);//无视了私有的构造器
        Reflex instance2=declaredConstructor.newInstance();//通过反射来new一个对象

        //如果被破坏,就是不一样的hashcode
        System.out.println(instance);
        System.out.println(instance2);
    }

}

解决方法,在构造器中加入锁

public class Reflex {
    private Reflex(){

        synchronized (Reflex.class){
            if (Reflex!=null) {
                throw new RuntimeException("不要试图用反射破坏异常");
            }
        }

        System.out.println(Thread.currentThread().getName()+"ok");
    }
    private volatile static Reflex Reflex;

    public static Reflex getInstance(){
        if (Reflex==null) {
            synchronized (Reflex.class){
                if (Reflex==null) {
                    Reflex=new Reflex();//不是一个原子性操作
                }
            }
        }
        return Reflex;
    }
}

可是如果在创建对象中,两个都是用反射来创建对象,那么得到的还是不一样的hashcode

public class Reflex {

    private static boolean bianliang=false;//红绿灯法,标识位,见多线程详解

    private Reflex() {

        synchronized (Reflex.class) {
            if (bianliang == false) {//不通过反编译,是找不到这个关键字的
                bianliang = true;
            } else {
                throw new RuntimeException("不要试图用反射破坏异常");
            }
        }
        System.out.println(Thread.currentThread().getName()+"ok");
    }
    private volatile static Reflex Reflex;

    public static Reflex getInstance(){
        if (Reflex==null) {
            synchronized (Reflex.class){
                if (Reflex==null) {
                    Reflex=new Reflex();//不是一个原子性操作
                }
            }
        }
        return Reflex;
    }

    public static void main(String[] args) throws Exception {//异常抛到最大

        Constructor<Reflex> declaredConstructor = Reflex.class.getDeclaredConstructor(null);//反射破坏单例,获取反射对象,拿到构造器,空参所以null
        declaredConstructor.setAccessible(true);//无视了私有的构造器
        Reflex instance2=declaredConstructor.newInstance();//通过反射来new一个对象
        Reflex instance=declaredConstructor.newInstance();//通过反射来new一个对象

        //如果被破坏,就是不一样的hashcode
        System.out.println(instance);
        System.out.println(instance2);
        
        
        //在构造器加入一个标识位,通过非当前的对象,谁都不知道,但假设找到了这个关键字但还是可以破坏的
        
        Field bianliang = Reflex.class.getDeclaredField("bianliang");//获取字段
        bianliang.setAccessible(true);//破坏
        

        Constructor<Reflex> declaredConstructor = Reflex.class.getDeclaredConstructor(null);//反射破坏单例,获取反射对象,拿到构造器,空参所以null
        declaredConstructor.setAccessible(true);//无视了私有的构造器
        Reflex instance2=declaredConstructor.newInstance();//通过反射来new一个对象
        bianliang.set(instance2,false);//值改回来

        Reflex instance=declaredConstructor.newInstance();//通过反射来new一个对象

        //如果被破坏,就是不一样的hashcode
        System.out.println(instance);
        System.out.println(instance2);
    }

}
@CallerSensitive
    public T newInstance(Object ... initargs)
        throws InstantiationException, IllegalAccessException,
               IllegalArgumentException, InvocationTargetException
    {
        if (!override) {
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, null, modifiers);
            }
        }
        // 通过反射的源码如果为枚举这里是不被允许创建实例的 因此通过枚举创建的单例模式是最安全的
        if ((clazz.getModifiers() & Modifier.ENUM) != 0)
            throw new IllegalArgumentException("Cannot reflectively create enum objects");
        ConstructorAccessor ca = constructorAccessor;   // read volatile
        if (ca == null) {
            ca = acquireConstructorAccessor();
        }
        @SuppressWarnings("unchecked")
        T inst = (T) ca.newInstance(initargs);
        return inst;
    }

Exception(“Cannot reflectively create enum objects”);
ConstructorAccessor ca = constructorAccessor; // read volatile
if (ca == null) {
ca = acquireConstructorAccessor();
}
@SuppressWarnings(“unchecked”)
T inst = (T) ca.newInstance(initargs);
return inst;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值