假设这里有一个我无法修改的 Button
对象,我想给它添加一些功能,例如让它可以拖动,所以我创建了一个类 Draggable
如下:
public class Draggable {
private Button button;
private Draggable(Button button) {this.button = button;}
// attach to a button
public static Draggable attachTo(Button button) {
return new Draggable(button);
}
// retrieve Draggable object attached to the button
public static Draggable of(Button button) {
// ...
}
// detatch from button
public static void detachFrom(Button button) {
Draggable d = of(button);
if (d != null) {d.button = null;}
}
}
每当 Button
对象被销毁并被垃圾收集时,附加到它的 Draggable
对象也应该自动成为垃圾收集器。那么有没有设计模式之类的东西可以帮我实现这个of()
方法呢?
最佳答案
您可能需要一个基于 WeakReferences 的内部缓存.
换句话说:您的 Draggalbe
只有在没有“硬” Activity 引用指向它时才能进行垃圾回收。
换句话说:
- 每次你创建一个
Draggabe
你把它放入你的缓存 - 如果弱引用缓存在缓存中仍然有效,你会定期检查缓存
- 当您发现变为
null
的弱引用时 - 您从缓存中删除该条目
当然 - 您必须确保没有其他“生命”对象保持对 Draggable
对象的硬引用。
关于java - 如何将 "attach"赋给一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45727674/