RAII in Java

これはアリなのか

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;
    }
};

コメント

コメントを入力. Wiki文法が有効です:
YQMMK
 
tips/java/raii.txt · 最終更新: 2014/01/06 23:44 (外部編集)
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0