Java - 设计模式之单例模式(枚举式)

枚举模式:最安全

package com.mmall.concurrency.example.singleton;

import com.mmall.concurrency.annoations.Recommend;
import com.mmall.concurrency.annoations.ThreadSafe;

/**
 * 枚举模式:最安全
 */
@ThreadSafe
@Recommend
public class SingletonExample7 {

    // 私有构造函数
    private SingletonExample7() {

    }

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

    private enum Singleton {
        INSTANCE;

        private SingletonExample7 singleton;

        // JVM保证这个方法绝对只调用一次
        Singleton() {
            singleton = new SingletonExample7();
        }

        public SingletonExample7 getInstance() {
            return singleton;
        }
    }
}
  • 相对于懒汉模式安全、性能更好;相对于饿汉模式只需第一次使用调用即可,不会造成资源浪费。
发布了1005 篇原创文章 · 获赞 1889 · 访问量 89万+

猜你喜欢

转载自blog.csdn.net/Dream_Weave/article/details/105507463