3

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).

3 Answers 3

5

It seems it's called a Multiton, or a registry of singletons. I don't think it's as well documented as a sigleton, but, as you noticed, it's really a more general version of a singleton, and shares the same set of strengths and weaknesses.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.