zoukankan      html  css  js  c++  java
  • 单例模式之饿汉方式实现与静态内部类实现的区别

    饿汉方式实现代码如下:

    package priv.jack.dp.demo.singleton;
    
    /**
     * @author Jack
     * 饿汉模式单例
     * 线程安全
     * 不支持懒加载,容易产生垃圾对象
     * 优点:没有加锁,执行效率会提高。
     */
    public class HungrySingleton {
    
        private static HungrySingleton INSTANCE = new HungrySingleton() ;
        
        private HungrySingleton() {
            System.out.println("init...");
        }
        
        public void hello() {
            System.out.println("hello  world!");
        }
        
        public static HungrySingleton getInstance() {
            return INSTANCE ;
        }
        
        public static void main(String [] args) {
            System.out.println("main start...");
            HungrySingleton.getInstance().hello(); 
        }
    }

    静态内部类实现代码:

    package priv.jack.dp.demo.singleton;
    
    /**
     * @author Jack
     * 支持懒加载,支持多线程
     * 对象在提一次使用时才被创建
     */
    public class StaticInnerSingleton {
    
        private static class StaticInnerSingletonHolder{
            private static final StaticInnerSingleton INSTANCE = new StaticInnerSingleton() ;
        }
        
        private StaticInnerSingleton() {
            System.out.println("init...");
        }
        
        public static final  StaticInnerSingleton getInstantce() {
            return StaticInnerSingletonHolder.INSTANCE ;
        }
        
        public void hello() {
            System.out.println("hello  world!");
        }
        
        
        public static void main(String [] args) {
            System.out.println("main start...");
            StaticInnerSingleton.getInstantce().hello(); 
        }
        
    }

    饿汉方式运行结果

    init...
    main start...
    hello  world!

    静态内部类方式运行结果

    main start...
    init...
    hello  world!

    区别在于,静态内部类方式是懒加载的,且兼顾高性能优点。

  • 相关阅读:
    【2019-08-03】自卑和悲观是有区别的
    你现在不用写代码了吧?
    【2019-08-02】信任是一种能力
    【2019-08-01】给孩子一个渴望长大的榜样
    【一句日历】2019年8月
    【2019-07-31】一切皆有寓意
    【2019-07-30】原来努力会上瘾
    【2019-07-29】睡多了,会被宰的
    【2019-07-28】活到老,学到老
    【2019-07-27】习惯的力量很强大
  • 原文地址:https://www.cnblogs.com/jack2013/p/5177814.html
Copyright © 2011-2022 走看看