處理具體類型時,比方說,我有下面的類層次結構:替代品的instanceof在Java中
public interface Result {
}
public class Failure implements Result {
private String msg;
public Failure(String msg) {
this.msg = msg;
}
@Override public String toString() { return msg; }
}
public class Success implements Result {
private int time, count;
public Success(int time, int count) { this.time = time; this.count = count; }
public int getTime() { return time; }
public int getCount() { return count; }
@Override public String toString() { return time + ", " + count; }
}
基本上定義包含兩個具體類的接口。結果:成功和失敗。
然後,我有一個返回結果,並根據結果我應該做的事情,例如一個計算方法:
Result result = calculate();
我有幾種選擇弄明白具體類。其中最明顯的是使用的實例:
if (result instanceof Success) {
int time = result.getTime();
int count = result.getCount();
// Do something with them
} else {
throw new RuntimeException(result.toString());
}
在比如Scala支持模式匹配的編程語言,我可以用一根火柴一樣
case Success =>
case Failure =>
但由於Java不支持的話,我我不確定最好做什麼。我可以例如延伸Result接口如下:
public interface Result {
public boolean isSuccess();
public boolean isFailure();
public Success asSuccess();
public Failure asFailure();
}
,然後編寫客戶端代碼爲:
if (result.isSuccess()) {
Success success = result.asSuccess();
int time = success.getTime();
int count = success.getCount();
// Do something with them
} else {
throw new RuntimeException(result.toString());
}
但在這種情況下,接口綁定具體類這也不好。
代表這種情況的最佳方式是什麼?我真的不想把處理代碼放在Result層次結構中,因爲它真的取決於客戶端來獲取數據並做他們想做的任何事情,所以多態調度解決方案可能不是最好的。結果層次至多是數據類型封裝,不是操作。