Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.