Created
June 20, 2011 16:20
-
-
Save sebersole/1035918 to your computer and use it in GitHub Desktop.
This file contains 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 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