Consider an interface that has only one method:
Object getValue(String data);
Suppose this describes data transformation from a String to any other data type (assuming the transformation is valid). For data coming from a textual context, there may be several columns that are of the same data type and thus there would be multiple instances of the same data transformer.
A long while ago I had written code to cache these instances instead of having multiple instances of the same object:
private HashMap<Class<? extends T>, T> map;
public synchronized T getInstance(Class<? extends T> type) throws IllegalArgumentException
{
T instance = map.get(type);
if (instance == null)
{
try
{
instance = type.newInstance();
}
catch (Exception ex)
{
throw new IllegalArgumentException("The provided class cannot be instantiated: "
+ type.getName() + "\n" + ex);
}
map.put(type, instance);
}
return instance;
}
Since these classes have no state, it seemed a waste, at the time to have many instances of the same class when a single shared instance would do.
However, it is likely more overhead to maintain the mapping than to have multiple instances of the same object (even though a single instance could be shared). I mean, even though there are multiple instances, the method code is only placed in memory once right? So in my mind, the JVM is effectively keeping a cache for me.
Any thoughts on the matter? Could the singleton instance-cache approach be better?
Thank you for reading my post.
Each time you use
new, you create a new object instance that is allocated in the heap. Of course, the executable code belongs to the class, which is only shared instance.Anyway, from your text, your object have no state and you are just transforming the String parameter using no additional data. Given that, I would go for an
staticmethod.