标签:
饿汉方式实现代码如下:
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!
区别在于,静态内部类方式是懒加载的,且兼顾高性能优点。
标签:
原文地址:http://www.cnblogs.com/jack2013/p/5177814.html