How can I specify the parameter when constructing a singleton object?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   roy_ngan
Posted On:   Tuesday, August 28, 2001 03:21 AM

I want to have a class that read common data from a file. I want to use singleton for this class to keep just a single copy for these common data. However, I want to specify the path for the file as a parameter. In using singleton, we usually use Myclass.getInstance(), which does not expect any parameter. On the other hand, if we allow parameter when getting the instance, what should be return if the parameter are different? If the parameter are different, it should be another instance, thus violate the principle of keeping one instance in a singleton. Or simply, in the above case, Singleton is not the proper design pattern? Then what should be the proper design so that the program won't keep dupli   More>>


I want to have a class that read common data from a file. I want to use singleton for this class to keep just a single copy for these common data. However, I want to specify the path for the file as a parameter.


In using singleton, we usually use Myclass.getInstance(), which does not expect any parameter.


On the other hand, if we allow parameter when getting the instance, what should be return if the parameter are different? If the parameter are different, it should be another instance, thus violate the principle of keeping one instance in a singleton.


Or simply, in the above case, Singleton is not the proper design pattern? Then what should be the proper design so that the program won't keep duplicate copies of these common data?

   <<Less

Re: How can I specify the parameter when constructing a singleton object?

Posted By:   Bernard_Choi  
Posted On:   Tuesday, August 28, 2001 03:55 AM

Consider using a Factory pattern with a cache. The factory itself would be a singleton, and you can get your MyClass via the factory.

Factory.getMyClassInstance(String param)

the factory would have to maintain the instance, and to return the same class if the parameter is repeated, or create a new one (and keep it in the cache) if it's a new parameter...
About | Sitemap | Contact