In JAVA I often use this pattern:
class A{
void addListener(Listener obj);
void removeListener(Listener obj);
}
class B {
private A a;
B(A a){
this.a=a;
a.addListener(myListener)
}
private final myListener=new Listener(){
void listener();
}
public void dispose(){
a.removeListener();
}
}
Typically A represents a dataset and B needs to respond to changes of the data in A. This is done by adding a listener to the object a when a new B instance is constructed.
Since the object a exists outside A, this approach forces me to create a dispose() method, that removes the listener from the object a.
Though I know that well designed JAVA code typically does not need dispose() methods. Is this pattern a poor design? Can you suggest alternative approaches?
Thanks in advance for your help.