设计模式(创建型--单例模式)

单例模式

设计模式(创建型--单例模式)_第1张图片
单例模式结构

实现单例模式的5种方式

1.饿汉式单例(立即加载方式)

public class Singleton{

    private Singleton(){};
    private static Singleton single = new Singleton();
    
    public static Singleton getInstance(){
        return single;
    }
}

2.懒汉式单例(延迟加载方式)

public class Singleton{

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

多线程环境下使用syhchronized

public class Singleton{

    private Singleton(){};
    private static Singleton single  =null ;
    
    public static Singleton getInstance(){
        // 等同于 synchronized public static Singleton getInstance()
        syhchronized(Singleton.class){
            if(Singleton  == null){
                Singleton = new Singleton();
            }
        }
    return Singleton ;
    }
}

利用双重检查提高效率

public class Singleton{

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

3.静态内部类实现

public class Singleton{

    private Singleton(){};
    
    private static class InnerClass {
        private static Singleton single  =new Singleton();
    }
    
    public static Singleton getInstance(){
        return InnerClass .single;
    }
}

4.静态代码块

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

5.内部枚举类实现

public class SingletonFactory {

    // 内部枚举类
   private enum EnmuSingleton{
        Singleton;
        private Singleton singleton;
         //枚举类的构造方法在类加载是被实例化 
        private EnmuSingleton(){
            singleton = new Singleton();
        }
        public Singleton getInstance(){
            return singleton;
        }
    }
    
    public static Singleton getInstance() {
          return EnmuSingleton.Singleton.getInstance();
    }
}

class Singleton{
    public Singleton(){}
}

你可能感兴趣的:(设计模式(创建型--单例模式))