设计模式-04-单例模式
本文参考自《Java与模式》
以及http://baike.baidu.com/view/1859857.htm
一、单例类的特点
1.某个类只能有一个实例。
2.构造器是private的(因此,单例类不能被继承)。
3.单例类必须自行创建自己的唯一实例。
二、单例的分类
1.饿汗式单例类
a.类图
b.Code
package com.jue.dp; public class EagerSingleton { private static final EagerSingleton instance = new EagerSingleton(); private EagerSingleton() { } public static EagerSingleton getInstance() { return instance; } }
2.懒汉式单例类
a.类图
b.Code
package com.jue.dp; public class LazySingleton { private static LazySingleton instance; private LazySingleton() { } public synchronized static LazySingleton getInstance() { if (instance == null) { instance = new LazySingleton(); } return instance; } }
3.双重检测
package com.jue.dp; public class DoubleLockSingleton { private static DoubleLockSingleton instance; private DoubleLockSingleton() { } public static DoubleLockSingleton getInstance() { if (instance == null) { synchronized (DoubleLockSingleton.class) { if (instance == null) { instance = new DoubleLockSingleton(); } } } return instance; } }
三、使用场景
1.一个系统要求一个类只有一个实例的时候。
2.整个项目需要一个共享访问点。
四、单例类的应用
Java.lang.Runtime对象
1.每个java应用程序里面都有唯一的一个 Runtime对象。
2.这个Runtime对象能够与器运行环境发生相互作用。
3.Runtime对象能够执行外部命令,查询内存信息,gc,加载动态库。
五、优点
1.保证了全局唯一。
2.内存中只有一个实例,减少了内存开支。
3.提供了一个全局访问点。
六、缺点
1.通过反射依然可以可以生成两个实例。