I have an abstract class A and several implementations of it. I expect this to change over time by adding more implementations.
I also have an interface that does something in instances of the above class hierarchy (e.g. prints them).
I want the interface implementations to provide some special functions for some subclasses of A and default functionality for the rest.
I hope this example clarifies the situation:
abstract class A { } class B extends A { } class C extends A { } interface Processor { public void process(A a); } class SimpleProcessor implements Processor {
This example prints "Default Processing". The problem is that the method that will be executed is selected based on the interface compilation time type. Is there a way (or a design pattern) for this program to print “Special Processing” without adding a list to line 14
if (a instance of B) process( (B) a );
for every class that needs special treatment?
I looked at visitor , but this does not seem to be an improvement, because I do not want to “foul” the processor interface with the methods for each subclass A, as more subclasses of A.
In other words, I want the implementation of the interface:
- provides a custom method implementation for specific subclasses of A
- provide a default implementation for classes to be added in the future
- avoid listing all classes in a large if-then-else list
Thanks!!
source share