Created
September 19, 2013 16:50
-
-
Save FredrikWendt/6626316 to your computer and use it in GitHub Desktop.
I väntan på closures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// higher order "method" (class) | |
public abstract class UseSafely<T> { | |
public abstract T with(AccountConnection connection); | |
public T runWith(AccountConnection connection) { | |
synchronized (connection) { | |
try { | |
connection.open(); | |
return with(connection); | |
} catch (Exception e) { ... } | |
} finally { | |
connection.close(); | |
} | |
} | |
} | |
} | |
public class WhereWeUseIt() { | |
// new | |
public int withdraw(AccountConnection connection, final int amount) { | |
return new UseSafely<Integer>() { | |
@Override | |
public Integer with(AccountConnection c) { | |
return c.withdraw(amount); | |
} | |
}.runWith(connection); | |
} | |
// old | |
public int withdraw(AccountConnection connection, int amount) { | |
synchronized (connection) { | |
try { | |
connection.open(); | |
return connection.withdraw(amount); | |
} catch (Exception e) { ... } | |
} finally { | |
connection.close(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment