简体   繁体   中英

How to avoid singleton in Android

I am working on an android app that reads long txt files, analyzes them and creates a java object containing some statistics extracted from the txt's. I used to have a singleton class that contained an array of these objects so that on the first call to the singleton class it would load the array of objects from a data file in storage, but after that it would always have the array in memory without the need to read from storage every time and allowing me to have access to the array from any activity. Also every time that a new txt was analyzed it would add the statistics object to the array and serialize it to storage.

Now this approach works flawlessly for me, but I've been reading that in android is recomended to avoid the use of singleton but I couldn't find any other way to obtain this same behaviour.

Could someone propose me a better solution or share some matherial explaining how to solve this please? My main concern is that I dont want to read from storage multiple times during the use of the app since that requires a few extra seconds.

There is nothing inherently wrong with the singleton pattern, assuming it is being used for some aspect of your model which is truly single. A singleton gets implemented using a static method. Static methods are avoided by people who do unit testing because they cannot be mocked or stubbed.

Now if you don't want to save the data and fetch it whenever required the data needs to be in memory to be available at all times. You can look at shared preferences if you find it useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM