I am trying to find the most elegant way to allow a child and parent to react to an event initiated by the grandparent. Here's a naive solution to this:
abstract class A {
final public void foo() {
// Some stuff here
onFoo();
}
protected abstract void onFoo();
}
abstract class B extends A {
@Override
final protected void onFoo() {
// More stuff here
onOnFoo();
}
protected abstract void onOnFoo();
}
class C extends B {
@Override
protected void onOnFoo() {
// Even more stuff here
}
}
So basically, I'm trying to find the best way to allow all related classes to perform some logic when foo() is called. For stability and simplicity purposes I prefer if it is all done in order, although it's not a requirement.
One other solution I found involves storing all the event handlers as some form of Runnable:
abstract class A {
private ArrayList<Runnable> fooHandlers = new ArrayList<>();
final public void foo() {
// Some stuff here
for(Runnable handler : fooHandlers) handler.run();
}
final protected void addFooHandler(Runnable handler) {
fooHandlers.add(handler);
}
}
abstract class B extends A {
public B() {
addFooHandler(this::onFoo);
}
private void onFoo() {
// Stuff
}
}
class C extends B {
public C() {
addFooHandler(this::onFoo);
}
private void onFoo() {
// More stuff
}
}
This method is certainly preferable to the first. However I am still curious if there is a better option.
Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.
Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).
Does a subclass have access to the members of a superclass? No, a superclass has no knowledge of its subclasses.
Have you considered the Template Method pattern? It works well to define a high level method that delegates to derived types to fill-in the gaps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With