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!

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

  • 相关阅读:
    Cefsharp支持MP4和MP3的CEF库cef.redist.x86.3.2623,对应Cefsharp49
    解读设计模式
    模拟支付宝、淘宝登录2
    模拟支付宝、淘宝登录1
    上一篇随笔是2011-11-21 17:23,唏嘘啊。。。
    像素格式
    YUV格式详解
    认识RGB和YUV
    WPF性能优化经验总结
    【日期正则表达式】
  • 原文地址:https://www.cnblogs.com/jack2013/p/5177814.html
Copyright © 2011-2022 走看看