Originally posted by Jacques Bosch:
I have implimented my Data class as a singleton.
I want to know, what is an elegant way to pass the location of my DB file to the singleton?
I do it in the instance() method. But I'm not sure this is the best way.
Only the first time instance() is called will the passed file be used.
But does that not go against the design of a singleton? Shouldn't the same method be called in the same way to get the same instance?
I think passing the DB file location into the instance method is entirely appropriate. It doesn't cause me any concerns at all. Would you have any concern with passing the DB file location into the constructor? Well, the instance method is just a wrapper for the constructor.
I made my Data class a singleton as well. The singleton design
pattern ensures that there will be no more than one instance of the Data class in the application. But before, I made my Data class a singleton, there was only one Data instance in the application anyway. You may
test this yourself with the following code:
The reason I'm using the singleton design pattern is to make it clear to anyone reading the code that there will be only one instance of this in the application.
So to get back to your concern over the calling instance method with the database file when it's only really needed the first time disappears in my case.
Even if instance was called multiple times in my application it still would not bother me that I'm supplying a database file with each call. After all, remember what instance does. It returns an instance of the Data class. Since it's a singleton it may return a previously constructed instance. But since instance must always be prepared to create a Data object, it follows that it needs to have all the information that you would normally give to the Data constructor.
To put this argument more concisely, don't be concerned about passing a parameter into the instance method. If still don't like this, realize that it's entirely possible your instance method will only be called once anyway.
Hope this helps,
George