Skip to content

Instantly share code, notes, and snippets.

@FredrikWendt
Created September 19, 2013 16:50
Show Gist options
  • Save FredrikWendt/6626316 to your computer and use it in GitHub Desktop.
Save FredrikWendt/6626316 to your computer and use it in GitHub Desktop.
I väntan på closures
// 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