如何在Android中避免使用单例模式

huangapple go评论72阅读模式
英文:

How to avoid singleton in Android

问题

我正在开发一个 Android 应用程序,用于读取长文本文件,对其进行分析,并创建一个包含从这些文本文件中提取的一些统计信息的 Java 对象。
我曾经有一个单例类,其中包含一个这些对象的数组,因此在首次调用单例类时,它会从存储中加载对象数组,但之后它将始终将数组保存在内存中,无需每次都从存储中读取,从而使我能够从任何活动中访问数组。
此外,每次分析新的文本时,都会将统计对象添加到数组中并将其序列化到存储中。

现在,这种方法对我来说运行得非常完美,但我一直在阅读关于在 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.

答案1

得分: 1

单例模式本身没有什么本质上的问题,假设它被用于模型中真正是单一的某个方面。单例模式通过使用静态方法来实现。单元测试时会避免使用静态方法,因为无法对其进行模拟或存根。

如果您不想保存数据并在需要时获取数据,那么数据需要始终驻留在内存中才能随时可用。如果您觉得有用,可以查看“共享首选项”(shared preferences)。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月6日 22:42:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63765371.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定