单例模式

概念

      单例模式是一个类模板,在整个系统运行过程中,有且只有一个实例,且只能New一个。

保证单例的技术方案

1、饿汉式

     在使用单列之前就产生了,不管你用不用都先new 出来,避免线程安全。(用的少,不存在线程安全问题)


public class Hungry {
    //私有构造方法
    private Hungry(){}
    //代码执行顺序
    //先静态、后动态
    //先属性、后方法
    //先上、后下
    private static  final  Hungry  hungry = new Hungry();
    public  static Hungry getInstance(){
        return hungry;
    }
}

2、懒汉式

        默认在加载的时候不实例化,在需要用到这个实例的时候在实例化(延时加载),

2.1静态内部类实现单例

public class LazySingleton {

    private LazySingleton(){}

    //静态内部类
    private static class LazyHolder{
        private static final  LazySingleton LAZY = new LazySingleton();
    }

    public static final LazySingleton getInstance(){
        return LazyHolder.LAZY;
    }
}

2.2双重锁实现单例

public class LazySingleton {  
    //使用volatile修饰该对象
    private static volatile LazySingleton instance;  
  
    private LazySingleton() {  
    }  
  
    public static LazySingleton getInstance() {  
        if (instance == null) {  
            synchronized (LazySingleton.class) {  
                if (instance == null) {  
                    instance = new LazySingleton();  
                }  
            }  
        }  
        return instance;  
    }  
}

3注册式单例

      第一次使用时,往一个固定的容器中去注册,并且将使用过的对象进行缓存,下次去取对象的时候就直接从缓存中取值,以保证每次获取的都是同一个对象,IOC 容器的单列模式,就是典型的注册登记式。

public class RegisterSingleton {

    private RegisterSingleton(){}

    private static ConcurrentHashMap<String,Object> register = new ConcurrentHashMap<String,Object>();

    public static RegisterSingleton getInstance(String name){
        if(name == null){
            name = RegisterSingleton.class.getName();
        }
        if(register.get(name) == null){
            register.put(name,new RegisterSingleton());
        }
        return  (RegisterSingleton) register.get(name);
    }
}

 

posted @ 2019-12-26 22:19  老木木  阅读(67)  评论(0)    收藏  举报