Java多线程 单例模式静态内部类&枚举写法

静态内部类(推荐使用)

如下为静态内部类的写法:

package com.thread.jmm;

/**
 * 类名称:Singleton1
 * 类描述:  静态内部类(推荐使用)
 *
 * @author: https://javaweixin6.blog.csdn.net/
 * 创建时间:2020/9/6 19:26
 * Version 1.0
 */
public class Singleton7 {

    /**
     * 单例模式的构造方法都是私有的, 防止其他对象new
     */
    private Singleton7() {
        //完成初始化等操作...
    }

    private static class SingletonInstance{
        private  static final Singleton7 INSTANCE = new Singleton7();
    }

    /**
     * 返回单例模式对象
     * @return
     */
    public static Singleton7 getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

该写法还是属于懒汉式, 因为使用的是内部类, jvm在加载类的时候, 一开始不会加载内部类, 不会有饿汉的一开始就加载资源的缺点. 并且JVM也保证了多个线程需要该实例的时候, 也不会创建多个实例.

枚举 (推荐实际生产使用)

如下为枚举的单例模式写法. 最简洁.

package com.thread.jmm;

/**
 * 类名称:Singleton1
 * 类描述:  枚举(推荐使用)
 *
 * @author: https://javaweixin6.blog.csdn.net/
 * 创建时间:2020/9/6 19:26
 * Version 1.0
 */
public enum  Singleton8 {
    //枚举提供的单例对象
    INSTANCE ;

    //单例模式提供的方法
    public void method() {

    }
}

枚举的单例模式举例如下, 在要使用的类的方法中, 直接用单例的类名.单例对象.方法名即可使用.

猜你喜欢

转载自blog.csdn.net/qq_33229669/article/details/108438511
今日推荐