Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java, singleton generalization

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

like image 333
AgostinoX Avatar asked May 06 '26 23:05

AgostinoX


1 Answers

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.

like image 183
socha23 Avatar answered May 10 '26 11:05

socha23



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!