单例模式

2021-02-26  本文已影响0人  编程的猫

保证程序中只有一个对象实例的存在

常见的四种单例实现方式:

public class InstancePattern {

    /**
     * Author imac
     * Time 2021/2/26 3:56 PM
     * Description 恶汉式单例,类加载的时候实现,线程不安全
     */
    public static class HungerInstance {
        private static HungerInstance instance = new HungerInstance();

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

    /**
     * Author imac
     * Time 2021/2/26 3:58 PM
     * Description 懒汉式单例,双重判断,线程安全
     */
    public static class LazyInstance {
        private static LazyInstance instance = null;

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

    /**
     * Author imac
     * Time 2021/2/26 4:02 PM
     * Description 枚举单例,线程安全
     */
    public static enum EnumInstance {
        INSTANCE,
    }

    /**
     * Author imac
     * Time 2021/2/26 4:03 PM
     * Description 内部类持有的单例,线程安全
     */
    public static class InnerClassInstance {
        private static class InnerHolder {
            protected static InnerClassInstance instance = new InnerClassInstance();
        }

        public static InnerClassInstance getInstance() {
            return InnerHolder.instance;
        }
    }


}
上一篇 下一篇

猜你喜欢

热点阅读