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?