继续设计模式,这个模式用得应该非常频繁啊,并且也比較简单,假设如今你还不能纸笔随手写个单例出来,你就得加油了哈~
直接介绍几种线程安全的且我认为还比較不错的方式:
1、是不是号称恶汉,就是类载入就初始化了
package com.zhy.pattern.singlton; public class Singleton { private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance ; } }2、懒汉,我喜欢这样的,须要双重推断
package com.zhy.pattern.singlton; public class Singleton02 { private static Singleton02 instance; public static Singleton02 getInstance() { if (instance == null) { synchronized (Singleton02.class) { if (instance == null) { instance = new Singleton02(); } } } return instance; } }
public enum Singleton03 { INSTANCE; }
package com.zhy.pattern.singlton; public class Singleton04 { private static final class InstanceHolder { private static Singleton04 INSTANCE = new Singleton04(); } public static Singleton04 getInstance() { return InstanceHolder.INSTANCE; } }
原文地址:http://www.cnblogs.com/mengfanrong/p/3850607.html