Created
December 22, 2012 18:12
-
-
Save anonymous/4360283 to your computer and use it in GitHub Desktop.
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
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