本文介绍Java单例模式的饿汉式和懒汉式的实现方法。
1、饿汉式
package singleton; /** * 饿汉式单例 * @author 蒋明原 * */ public class HungrySingleton { /**jvm保证instance只被初始化一次*/ private static HungrySingleton instance = new HungrySingleton(); /**阻止外部使用new实例化对象*/ private HungrySingleton(){ } /** * 获取实例 * @return 唯一的instance */ public static HungrySingleton getInstance() { return instance; } } |
2、懒汉式
package singleton; /** * 懒汉式单例 * @author 蒋明原 * */ public class LazySingleton { /** * 阻止外界使用new实例化对象 */ private LazySingleton() { } /** * 只有在调用getInstance()时此类才会被装载 * 在SingletonKerriganF.java中说明了加载顺序 */ private static class SingletonHolder { /** * 对象实例,jvm保证只初始化一次 */ static final LazySingleton INSTANCE = new LazySingleton(); } /** * 获取实例 * @return 返回唯一实例 */ public LazySingleton getInstance() { return SingletonHolder.INSTANCE; } } |
3、懒汉式单例内部类加载顺序 (来自http://www.javaeye.com/topic/575052)
package singleton; /** * 实现单例访问Kerrigan的第六次尝试 * @author IcyFenix * @see http://www.javaeye.com/topic/575052 */ public class SingletonKerriganF { private static String arg = null; private static class SingletonHolder { /** * 单例对象实例 */ static final SingletonKerriganF INSTANCE = new SingletonKerriganF(); } public static SingletonKerriganF getInstance() { return SingletonHolder.INSTANCE; } public SingletonKerriganF() { System.out.println("Kerrigan get arg:" + getArg()); System.out.println("Kerrigan created!"); } public static String getArg() { return arg; } public static void setArg(String arg) { SingletonKerriganF.arg = arg; } public static void main(String[] args) { System.out.println("SingletonKerriganF was loaded,but SingletonKerriganF$SingletonHolder don't"); SingletonKerriganF.setArg("this maybe some config files etc...."); SingletonKerriganF.getInstance(); } } |
http://webservices.ctocio.com.cn/java/318/9411318.shtml