Release resource
public interface Disposable {
void dispose();
}
public abstract class Using<T extends Disposable> {
public Using(T obj) {
try {
run(obj);
} finally {
obj.dispose();
}
}
public abstract void run(T obj);
}
public class Resource implements Disposable {
public void dispose() {
// Release resource
}
}
new Using<Resource>(new Resource()) {
public void run(Resource obj) {
// Do something
}
};
Transaction
public abstract class Transaction {
public Transaction(DAO dao) {
boolean res = false;
dao.beginTransaction();
try {
res = run();
} finally {
if(res) {
dao.commit();
} else {
dao.rollback();
}
}
}
public abstract boolean run();
}
final DAO dao = DAOFactory.create(...);
new Transaction(dao) {
public boolean run() {
dao.executeUpdate("INSERT INTO hoge VALUES (?, ?)", "3", "foo");
dao.executeUpdate("INSERT INTO hoge VALUES (?, ?)", "4", "bar");
return true;
}
};