编码时。尝试解决这个难题:
InputStreamDigestComputor 抛出 IOException 时如何设计类/方法?
由于模板方法抛出异常,但覆盖方法不抛出异常,我们似乎无法使用此设计结构。但是如果改变被覆盖的方法来抛出它,会导致其他子类都抛出它。那么对于这种情况有什么好的建议吗?
abstract class DigestComputor{
String compute(DigestAlgorithm algorithm){
MessageDigest instance;
try {
instance = MessageDigest.getInstance(algorithm.toString());
updateMessageDigest(instance);
return hex(instance.digest());
} catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage(), e);
throw new UnsupportedOperationException(e.getMessage(), e);
}
}
abstract void updateMessageDigest(MessageDigest instance);
}
class ByteBufferDigestComputor extends DigestComputor{
private final ByteBuffer byteBuffer;
public ByteBufferDigestComputor(ByteBuffer byteBuffer) {
super();
this.byteBuffer = byteBuffer;
}
@Override
void updateMessageDigest(MessageDigest instance) {
instance.update(byteBuffer);
}
}
class InputStreamDigestComputor extends DigestComputor{
// this place has error. due to exception. if I change the overrided method to throw it. evey caller will handle the exception. but
@Override
void updateMessageDigest(MessageDigest instance) {
throw new IOException();
}
}