如何“附加”到对象

时间:2017-08-17 06:05:27

标签: java

假设这是一个我无法修改的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()方法吗?

1 个答案:

答案 0 :(得分:1)

您可能需要基于WeakReferences的内部缓存。

换句话说:当没有“硬”活动引用指向它时,您的Draggalbe只能进行垃圾回收。

换句话说:

  • 每次创建Draggabe时,都会将其放入缓存
  • 如果缓存中的弱引用仍然有效,则定期检查缓存
  • 当您找到转向null的弱引用时 - 从缓存中删除条目

当然 - 你必须确保 no 其他“生命”对象保持对Draggable对象的硬引用。

有关详细信息,请参阅herethere

相关问题