Reputation: 7683
Given:
File f = new File("test.txt");
this way, each time i create a reference to the file "text.txt", i get a different File object.
I need that if the file is the same, then I get the same File
object.
(To be precise and coherent with the example, it is the canonical path that has to be the same, but since this is just an example, i don't want to go in deep with files identities)
It can be quite easily implemented with a static getInstance that tests the previously created File instances, stored in a Collection and returns the stored one if present.
This seems to be a "more general singleton pattern", where singleton means one instance per application, while here we have one instance each distinct identity (in the example, each file path will have only one File object).
The question is, since singleton is well documented (and perhaps over-documented) is this pattern "described" and standardized too?
(This is exactly what happens in certain jvm implementations for Integers<128 for optimization purposes and not to rely on).
Upvotes: 3
Views: 255
Reputation: 169551
Isn't what you really want just a CachedReader
?
pseudo::
class CachedConstructor {
private Object[] cachedThings
private Object constructor
public CachedConstructor(Object thing) {
this.constructor = thing;
}
public Object getThing(string data) {
if (loc in cachedFiles) {
return getThingFromCache();
}
return putThingInCache(data);
}
}
new CachedConstructor(File);
Upvotes: 1
Reputation: 5436
Maybe you'll find inversion of control and dependency injection interesting for your case.
This article is a nice read on singletons vs DI. http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/
Checkout Guice for example.
Upvotes: 1