JSPDeveloper01 JSPDeveloper01 - 5 months ago 38
Java Question

How to "attach" to an Object

Assume here is a

object which I cannot modify, and I want to add some function to it, making it draggable for example, so I create a class
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
object is destroyed and garbage collected, the
object attached to it should also be garbage collectable automatically. So is there a design pattern or something that can help me implement this

Answer Source

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.