假设这是一个我无法修改的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()
方法吗?
答案 0 :(得分:1)
您可能需要基于WeakReferences的内部缓存。
换句话说:当没有“硬”活动引用指向它时,您的Draggalbe
只能进行垃圾回收。
换句话说:
Draggabe
时,都会将其放入缓存null
的弱引用时 - 从缓存中删除条目当然 - 你必须确保 no 其他“生命”对象保持对Draggable
对象的硬引用。