2

Assume here is a Button object which I cannot modify, and I want to add some function to it, making it draggable for example, so I create a class Draggable as follows:

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;}
    }
}

Whenever the Button object is destroyed and garbage collected, the Draggable object attached to it should also be garbage collectable automatically. So is there a design pattern or something that can help me implement this of() method?

JSPDeveloper01
  • 770
  • 2
  • 10
  • 25

1 Answers1

1

You probably need an internal cache based on WeakReferences.

In other words: your Draggalbe can only be subject to garbage collection when no "hard" alive reference is pointing to it.

In other words:

  • every time you create a Draggabe you put that into your cache
  • you periodically check the cache if the weak references cached in there are still valid
  • when you find a weak reference that turned null - you delete the entry from the cache

And of course - you have to make sure that no other "life" object keeps a hard reference to a Draggable object.

See here and there for further reading.

GhostCat
  • 137,827
  • 25
  • 176
  • 248