|
package cube.com.helper; |
|
|
|
import java.util.WeakHashMap; |
|
|
|
import lombok.Getter; |
|
|
|
/** |
|
* Singleton class used for passing large data sets around without having to serialise. |
|
* This class should <b>not</b> reference any kind of context without implicitly destroying |
|
* the object when it is done to prevent Context leaks. Be wary! |
|
* |
|
* @author Callum Taylor |
|
*/ |
|
public class IntentDataHelper |
|
{ |
|
@Getter(lazy = true) private static final IntentDataHelper instance = new IntentDataHelper(); |
|
|
|
private WeakHashMap<Class, Object> dataStore = new WeakHashMap<>(); |
|
|
|
/** |
|
* Stores object data against a class name. Operation is destructive, if {@param className} already exists in the data store map. |
|
* |
|
* @param className The class to store against, use the same class name to retrieve the data back. |
|
* @param data The data to temporarily store. |
|
*/ |
|
public void store(Class className, Object data) |
|
{ |
|
dataStore.put(className, data); |
|
} |
|
|
|
/** |
|
* Gets the stored data object from a given className, or null if nothing was stored. Operation is destructive, |
|
* object will be removed from data store once retrieved. |
|
* |
|
* @param className The class name used to originally store the data |
|
* @return The found object or null. |
|
*/ |
|
public Object retrieve(Class className) |
|
{ |
|
return retrieve(className, Object.class); |
|
} |
|
|
|
/** |
|
* Gets the stored data object from a given className, or null if nothing was stored. Operation is destructive, |
|
* object will be removed from data store once retrieved. |
|
* |
|
* @param className The class name used to originally store the data |
|
* @param classType The class type to force cast to |
|
* @return The found object or null. |
|
*/ |
|
public <T> T retrieve(Class className, Class<T> classType) |
|
{ |
|
return (T)classType.cast(dataStore.remove(className)); |
|
} |
|
|
|
/** |
|
* Force destroys the data store to remove all references |
|
*/ |
|
public void clear() |
|
{ |
|
dataStore = new WeakHashMap<>(); |
|
} |
|
} |