如何在没有内存泄漏的情况下在单例类中保存按钮引用 [英] How to hold Button reference in singleton class without memory leak
问题描述
我有一个单例util"类.这个类对 UI 元素做了很多操作(带有一些自定义按钮、edittext 等),所以每次使用 util 类时传递所有 ui 对象的引用是很不舒服的.所以我创建了一个设置"方法,比如
I have a singleton 'util' class. This class is doing a lot of operation with UI elements (with some custom button, edittext etc.), so it's quite uncomfortable to pass all of the ui object's reference every time I use the util class. So I created a 'setup' method, like
public void setStatusButtons (Button button1, Button button2, etc... ) {
this.mButton1 = button1;
this.mButton2 = button2;
etc...
}
然后,如果我想使用它们,只需使用 mButton1、mButton2 ... 字段.
Then if I want to use them just use the mButton1, mButton2 ... fields.
但是这个解决方案有问题.它可能会导致内存泄漏.足以创建一个免费"方法(并在 onDestroy() 或类似的东西中调用它),例如:
But there is a problem with this solution. It can cause a memory-leak. Is enough to create a 'free' method (and call it in onDestroy() or something like that), like:
public void freeObjects () {
this.mButton1 = null;
this.mButton2 = null;
etc...
}
或者这是一个非常可怕和hacky的解决方案,还有一些更好的解决方案?:)
or it's a very horrible and hacky solution and there is some nicer ? :)
现在在 util 类中我有 15 个方法(这个数字在项目结束时可以更多),所以我真的不想每次都传递 UI 对象的引用,如果我不需要的话.
In the util class now I have 15 methods (and this number can be more at the end of the project), so I really don't want to pass every time the UI object's reference, if I don't have to.
谢谢.
推荐答案
或者这是一个非常可怕和hacky的解决方案,还有一些更好的
or it's a very horrible and hacky solution and there is some nicer
摆脱单身.然后:
使用继承,让您的活动/片段扩展一些包含您的实用程序代码的基类
Use inheritance, with your activities/fragments extending some base class that has your utility code
或者,使用组合,其中您的活动/片段使用您的实用程序代码创建类的实例,而不是使用单个全局内存泄漏实例
Or, use composition, where your activities/fragments create an instance of your class with your utility code, rather than having a single global memory-leaking instance
这篇关于如何在没有内存泄漏的情况下在单例类中保存按钮引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!