问题
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...
}
Then if I want to use them just use the mButton1, mButton2 ... fields.
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...
}
or it's a very horrible and hacky solution and there is some nicer ? :)
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.
Thanks.
回答1:
or it's a very horrible and hacky solution and there is some nicer
Get rid of the singleton. Then:
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
来源:https://stackoverflow.com/questions/43942723/how-to-hold-button-reference-in-singleton-class-without-memory-leak