このコードを見てください:
IDfSessionManager manager = DfcSessionManager.getSessionManager();
try {
IDfSession session = manager.getSession(DfsUtils.getCurrentRepository());
...
return somewhat; //May be without return statement
} finally {
if (session != null) {
manager.release(session);
}
}
このような構造が何度も繰り返され、さまざまなコードが取り囲まれます。これは、return ステートメントの有無にかかわらずメソッドにすることができます。この try-finally ブロックを再利用できるようにしたいと考えています。
私はそのような認識から考え出しました。
public abstract class ISafeExecute<T> {
private IDfSession session = null;
protected abstract T execute() throws DfException;
public T executeSafely() throws Exception {
IDfSessionManager manager = DfcSessionManager.getSessionManager();
try {
session = manager.getSession(DfsUtils.getCurrentRepository());
return execute();
} finally {
if (session != null) {
manager.release(session);
}
}
}
public IDfSession getSession() {
return session;
}
}
セッションフィールドは public getter で作成しました。
そして、このクラスを次のように使用できます(返されたオブジェクトを使用):
return new ISafeExecute<String>() {
@Override
public String execute() throws DfException {
return getSession().getLoginTicket();
}
}.executeSafely();
または戻りオブジェクトなし:
new ISafeExecute() {
@Override
public Object execute() {
someMethod();
return null;
}
}.executeSafely();