Android 设计模式入门到精通之一:单例模式(Singleton)

版权声明:本文为博主原创文章,未经允许不得转载,如有问题,欢迎指正,谢谢! https://blog.csdn.net/cbk861110/article/details/88070929

设计模式项目源码请移步:https://github.com/caobaokang419/WeatherApp(欢迎Github Fork&Star,代码设计模式&框架设计实现不妥之处,请帮忙指正),谢谢!

单例模式(Singleton

一、概念及技术背景

单例对象(Singleton)是一种常用的设计模式。在Java应用中,单例对象能保证在一个JVM中,该对象只有一个实例存在。这样的模式有几个好处:

1、某些类创建比较频繁,对于一些大型的对象,这是一笔很大的系统开销。

2、省去了new操作符,降低了系统内存的使用频率,减轻GC压力。

3、有些类如交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了。(比如一个军队出现了多个司令员同时指挥,肯定会乱成一团),所以只有使用单例模式,才能保证核心交易服务器独立控制整个流程。

二、代码实践(Thread-Safe demo codes)

1. 实现方式1:延迟实例化

public class DownloadManager {
    private volatile static DownloadManager mInstance;
    private DownloadManager(Context context) {
        mContext = context;
    }

    /*双重检查加锁,减少使用同步*/
    public static DownloadManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (DownloadManager.class) {
                if (mInstance == null) {
                    mInstance = new DownloadManager(context);
                }
            }
        }
        return mInstance;
    }
}

2. 实现方式2:非延迟实例化

public class CityInfoUtil {
    private static CityInfoUtil mInstance = new CityInfoUtil();

    /*私有构造,限制用户自行实例化*/
    private CityInfoUtil() {
    }

    public static CityInfoUtil getInstance() {
        return mInstance;
    }
}

猜你喜欢

转载自blog.csdn.net/cbk861110/article/details/88070929