看看这段代码:
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;
}}
会话字段是用公共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();发布于 2012-08-15 20:59:21
您可以使用Runnable<T>构建一种机制来实现这一点(某种程度上是将一个函数注入另一个函数):
public void runInSession(Runnable<IDfSession> runnable) {
IDfSession session = null;
try {
session = manager.getSession(DfsUtils.getCurrentRepository());
runnable.run(session);
} finally {
if (session != null) {
manager.release(session);
}
}
}你也可以使用更多的泛型来返回值。我这里缺少Java编译器,而且我对语法不太确定。
编辑,因为我看到了你的编辑:
使用定制的ISafeExecute接口可能比使用Runnable<T>更简洁,但其思想是相同的。您可以构建它,以便可以优雅地放置返回值(或错误):
interface ISafeExecute<T> {
void execute(IDfSession session);
T getResult();
Exception getException();
}
mySafeExecute.execute(session);
if(mySafeExecute.getException() == null) {
return mySafeExecute.getResult();
} else {
// runtime exception or declaration in method
// signature
throw new RuntimeException(mySafeExecute.getException());
}发布于 2012-08-16 16:17:19
我有这样的决定:
public abstract class SafeExecute<T> {
protected IDfSession session = null;
public T executeSafely() throws Exception {
IDfSessionManager manager = DfcSessionManager.getSessionManager();
try {
session = manager.getSession(DfsUtils.getCurrentRepository());
return logic();
} finally {
if (session != null) {
manager.release(session);
}
}
}
protected abstract T logic() throws Exception;
}然后通过扩展这个类:
public class Service extends SafeExecute<String> {
public String getLoginTicket() throws Exception {
return executeSafely();
}
@Override
protected String logic() throws Exception {
//TODO implement
}
}https://stackoverflow.com/questions/11969619
复制相似问题