该访问者模式通常在这样的情况下使用。尽管代码有些复杂,但是添加新的
RecordType子类后,您
必须 在所有地方实现逻辑,否则它将无法编译。与
instanceof所有的地方也很容易错过一个或两个地方。
例:
public abstract class RecordType { public abstract <T> T accept(RecordTypeVisitor<T> visitor);}public interface RecordTypeVisitor<T> { T visitOne(RecordType1 recordType); T visitTwo(RecordType2 recordType);}public class RecordType1 extends RecordType { public <T> T accept(RecordTypeVisitor<T> visitor) { return visitor.visitOne(this); }}public class RecordType2 extends RecordType { public <T> T accept(RecordTypeVisitor<T> visitor) { return visitor.visitTwo(this); }}用法(请注意通用返回类型):
String result = record.accept(new RecordTypeVisitor<String>() { String visitOne(RecordType1 recordType) { //processing of RecordType1 return "Jeden"; } String visitTwo(RecordType2 recordType) { //processing of RecordType2 return "Dwa"; }});我也建议抛出一个异常:
throw new IllegalArgumentException(record);
而不是在
null找不到这两种类型时返回。



