我同意访客的使用。
此外,如果您无权访问 Ball 层次结构(源代码访问)或者只是不想在那里修改任何内容;您可以修改您的客户类并从那里决定。
坏事当然是你会得到很多 if/elseif 语句。
您需要添加通用方法 ( add( Ball ) ) 并从那里调用其他方法。这是快速、简单和肮脏的。
:)
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 {}
顺便说一句,如果您没有直接引用,编译器会将其发送到最后 2 次调用中的正确方法。
如您所见,您只需要添加以下代码:
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 );
}
}