java 中的单例模式,三种最佳实例

一、两种简单实现

1、饿汉式,即直接静态初始化

优点:简单,含有 final 关键字
缺点:程序运行直接加载,耗费资源

public class SingletonObject1 {

    private static final SingletonObject1 instance = new SingletonObject1();

    private SingletonObject1(){}

    public static SingletonObject1 getInstance(){
        return instance;
    }
}

2、懒汉式 - synchronized 实现

优点:懒加载实现,即初次获取值时才会初始化
缺点:synchronized 实现,初始化后每次读操作也会加锁,耗费资源

public class SingletonObject3 {

    private int num = 10;
    private static SingletonObject3 instance;

    private SingletonObject3(){
        this.num = new Random().nextInt(10);
    }

    public synchronized static SingletonObject3 getInstance() {
        if (instance == null){
           instance = new SingletonObject3();
        }
        return instance;
    }

}

二、三种最佳实例实现

1、懒汉式 - synchronized 双重检查 实现

优点:懒加载 + 双重检查,确保初始化一次,同时优化性能
缺点:实现较复杂,同时 volatile 也有性能损耗

public class SingletonObject4 {

    private int num = 10;
    private static volatile SingletonObject4 instance;

    private SingletonObject4(){
        this.num = new Random().nextInt(10);
    }

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

2、内部类 - Holder方式实现

优点:使用内部类机制实现懒加载,最佳实践之一

public class SingletonObject5 {

    private int num = 10;

    private SingletonObject5(){
        this.num = new Random().nextInt(10);
    }

    private static class SingletonHolder{
        private final static SingletonObject5 instance = new SingletonObject5();
    }

    public static SingletonObject5 getInstance(){
        return SingletonHolder.instance;
    }

}

3、枚举方式实现

优点:使用枚举机制实现懒加载,语义上较为优雅,最佳实践之一

public class SingletonObject6 {

    private int num = 10;

    private SingletonObject6(){
        this.num = new Random().nextInt(10);
    }

    private enum Singleton{

        INSTANCE;

        private final SingletonObject6 instance;

        Singleton(){
            instance = new SingletonObject6();
        }

        private SingletonObject6 getInstance(){
            return instance;
        }
    }

    public static SingletonObject6 getInstance(){
        return Singleton.INSTANCE.getInstance();
    }

}

你可能感兴趣的:(多线程学习,java,单例模式,开发语言)