I agree with the use of the visitor.
In addition, if you do not have access to the Ball hierarchy (access to the source code) or just do not need to change anything; You can change your client class and decide from there.
Bad, of course, you get a lot of if / elseif statements.
You will need to add a general method (add (Ball)) and from there call the rest. It is fast, easy and dirty.
:)
public class Test { public static void main( String [] args ) { Ball ball = new IllegalBall(); Test test = new Test(); test.add( ball ); test.add( new IllegalBall() ); test.add( new LegalBall() ); } private void add( Ball ball ){ System.out.println("Generic method: I'll have someone handling this : " + ball ); if( ball instanceof IllegalBall ) { add( ( IllegalBall ) ball ); } else if( ball instanceof LegalBall ) { add( ( LegalBall ) ball ); } } private void add( IllegalBall ball ){ System.out.println("illega-ball: I won't do anything about it! " + ball ); } private void add( LegalBall ball ) { System.out.println("legal-ball: Hey this is legal I'll do my best!! " + ball ); } } class Ball {} class IllegalBall extends Ball {} class LegalBall extends Ball {}
BTW, if you don’t have the link directly, the compiler will send it to the correct method, as in the last two calls.
As you can see, you just need to add the following code:
private void add( Ball ball ){ System.out.println("Generic method: I'll have someone handling this : " + ball ); if( ball instanceof IllegalBall ) { add( ( IllegalBall ) ball ); } else if( ball instanceof LegalBall ) { add( ( LegalBall ) ball ); } }
source share