设计模式之单例模式(Singleton)
单例模式是一种常用的设计模式,可以保证对象在JVM中只有一个实例存在,这样做的好处可以不用重复的创建类对象,节省一笔很大的开销,而且可以减轻GC压力。常见的创建模式有懒汉模式和饿汉模式。但是如果考虑到不同场景,设计有很大差别。
首先简单一个简单的图示例:
懒汉模式:(类加载时,不立即创建实例,所以加载类速度快,但是获取实例较慢)
- public class SingIeton {
- /*
- * 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载
- */
- private static SingIeton instance = null;
- /*
- *私有构造方法,防止被实例化
- */
- private SingIeton(){
- }
- /*静态工程方法,创建实例*/
- public static SingIeton getInstance(){
- if(instance == null){
- instance = new SingIeton();
- }
- return instance;
- }
- }
饿汉模式:(类加载时,创建实例,加载速度慢,但是获取实例快)
- public class SingIeton {
- private static SingIeton instance = new SingIeton();
- /*
- *私有构造方法,防止被实例化
- */
- private SingIeton(){
- public static SingIeton getInstance(){
- return instance;
- }
- }
如果放在多线程下,上面的写法显然是不安全的,要考虑到同步问题:
- public class SingIeton {
- /*
- * 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载
- */
- private static SingIeton instance = null;
- /*
- *私有构造方法,防止被实例化
- */
- private SingIeton(){
- }
- /*静态工程方法,创建实例*/
- public static synchronized SingIeton getInstance(){
- if(instance == null){
- instance = new SingIeton();
- }
- return instance;
- }
- }
- /**
- * Created by diy_os on 2016/10/2.
- */
- public class SingIeton {
- /*
- * 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载
- */
- private static SingIeton instance = null;
- /*
- *私有构造方法,防止被实例化
- */
- private SingIeton(){
- }
- public static SingIeton getInstane(){
- if(instance == null){
- synchronized (instance){
- if(instance == null){
- instance = new SingIeton();
- }
- }
- }
- return instance;
- }
- }
上面的写法在一定程度上提升了性能,但不是最优的,单例模式需要结合实际需求找到适合的解决方法,有一定的难度。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29876893/viewspace-2140450/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29876893/viewspace-2140450/