单例模式不同写法

饿汉式(上来就是干)

优点:线程安全、调用效率高
缺点:不能延时加载,不用的时候回浪费资源

/**
 * @author wyd
 * @description 类加载的时候天然线程安全,不用加同步块
 * @date 2019/3/20 下午3:54
 */
public class SingletonTest1 {
    private static SingletonTest1 instance = new SingletonTest1();

    private SingletonTest1() {
    }

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

懒汉式(延时)

  • 单例对象延时加载
    优点:用的时候加载,资源利用高
    缺点:并发效率低
public class SingletonTest2 {
    private static SingletonTest2 instance;

    private SingletonTest2() {
    }

    public static SingletonTest2 getInstance() {
        //如果同步块放到这里则会影响效率,如果存在对象直接返回
        if (instance == null) {//提高效率
            synchronized (SingletonTest2.class) {
                if (instance == null) {//安全
                    instance = new SingletonTest2();
                }
            }
        }
        return instance;
    }
}
  • 静态内部类方式实现
    优点:调用getInstance的时候才会去加载静态内部类,而且是线程安全的,并发高效,延时加载
public class SingletonTest3 {
    private SingletonTest3() {
    }

    private static class SingletlonInstance {
        private static final SingletonTest3 instance = new SingletonTest3();
    }

    public static SingletonTest3 getInstance() {
        return SingletlonInstance.instance;
    }
}

枚举实现

优点:枚举自身就是单例模式,天然线程安全,同时可以避免反序列化和反射的漏洞
缺点:无延时

public enum SingletonEnum {
    INSTANCE;

    public void singletonOperation() {
        //相关操作
        System.out.println("我是枚举的单例啊啊啊啊啊");
    }
}
该如何用呢?
  • 单例的对象如果占用的资源少,不需要延时加载,枚举优于饿汉式
  • 单例的对象如果占用的资源大,需要延时加载,静态内部类优于懒汉式

如果有问题,请留言,相互探探讨哦^

上一篇-设计模式概述

你可能感兴趣的:(单例模式不同写法)