1.什么是单例模式?
保证类仅有一只示例,并提供一个访问它的全局访问点。
2.单例模式类图
3.java 实现
a.饿汉模式
package com.jerry.pattern.singleton; /** * 单例模式 * 饿汉子模式 * @author Jerry * * 2014-1-23 下午01:50:25 */ public class HungrySingleton { private static HungrySingleton singleton = new HungrySingleton(); private HungrySingleton() {} public static HungrySingleton getInstance() { return singleton; } }
b.懒汉模式
package com.jerry.pattern.singleton; import java.util.concurrent.locks.ReentrantLock; /** * 单例模式 * 懒汉模式 * @author Jerry * * 2014-1-23 下午01:51:46 */ public class LazySingleton { private static LazySingleton singleton = null; private static ReentrantLock lock = new ReentrantLock(); private LazySingleton() {} public static LazySingleton getInstance() { if (singleton == null) { try { lock.lock(); if (singleton == null) { singleton = new LazySingleton(); } } finally { // TODO: handle exception lock.unlock(); } } return singleton; } }
c.内部类模式
package com.jerry.pattern.singleton; /** * 内部类 * @author Jerry * * 2014-1-27 上午10:44:33 */ public class InnerClassSingleton { private static InnerClassSingleton singleton; private InnerClassSingleton() { } public InnerClassSingleton getInstance() { if (singleton == null) { singleton = InnerClass.singleton; } return singleton; } private static class InnerClass { private static InnerClassSingleton singleton = new InnerClassSingleton(); } }
d.枚举模式
package com.jerry.pattern.singleton; /** * 枚举单例 * @author Jerry * * 2014-1-27 上午10:49:51 */ public enum EnumSingleton { /** * 定义一个枚举元素 */ uniqueSingleton; public void singletonOperation() { } }