Skip to content

Instantly share code, notes, and snippets.

@sebersole
Created June 20, 2011 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebersole/1035918 to your computer and use it in GitHub Desktop.
Save sebersole/1035918 to your computer and use it in GitHub Desktop.
public class Value<T> {
/**
* The snippet that generates the initialization value.
*
* @param <T>
*/
public static interface DeferredInitializer<T> {
/**
* Build the initialization value.
* <p/>
* Implementation note: returning {@code null} is "ok" but will cause this method to keep being called.
*
* @return The initialization value.
*/
public T initialize();
}
private final DeferredInitializer<T> valueInitializer;
private T value;
/**
* Instantiates a {@link Value} with the specified initializer.
*
* @param valueInitializer The initializer to use in {@link #getValue} when value not yet known.
*/
public Value(DeferredInitializer<T> valueInitializer) {
this.valueInitializer = valueInitializer;
}
@SuppressWarnings( {"unchecked"})
public Value(T value) {
this( NO_DEFERRED_INITIALIZER );
this.value = value;
}
public T getValue() {
if ( value == null ) {
value = valueInitializer.initialize();
}
return value;
}
private static final DeferredInitializer NO_DEFERRED_INITIALIZER = new DeferredInitializer() {
@Override
public Object initialize() {
return null;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment