Skip to content

Instantly share code, notes, and snippets.

Created December 22, 2012 18:12
Show Gist options
  • Save anonymous/4360283 to your computer and use it in GitHub Desktop.
Save anonymous/4360283 to your computer and use it in GitHub Desktop.
public class EnterableScope implements Scope
{
private HashMap<Key<?>, Object> values;
public void enter()
{
values = new HashMap<Key<?>, Object>();
}
public void exit()
{
values = null;
}
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped)
{
return new Provider<T>() {
@Override
@SuppressWarnings("unchecked")
public T get()
{
// if values is null return null otherwise return the stored value of one exists
Object object = values != null ? values.get(key) : null;
if(object == null)
{
object = unscoped.get();
// if we in scope, store it, otherwise always create a new one
if(values != null)
{
values.put(key, object);
}
}
return (T) object;
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment