Meaningless Drivel is fun!*
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes Singleton / Factory decision Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "Singleton / Factory decision" Watch "Singleton / Factory decision" New topic
Author

Singleton / Factory decision

Mark Thomson
Greenhorn

Joined: Jul 20, 2004
Posts: 15
I want to have a DBSchema class that basically stores my db schema information and also returns me a single instance of a RandomAccessFile.

Now I can't decide between implementing as follows:

1. Implement DBSchema as a singleton. Now the issue I have is that I want the DBSchema object to be responsible for reading in the schema from the dbFile so it will need to get hold of the file path. To do this I need to have a static method, say init(String dbPath) and then some boolean flags ( or throw exceptions )to say if I've already called init() on the singleton. Now I don't really like using the singleton pattern in this way as I am forced to have to make sure I call init() before I call getInstance() to get hold of the singleton DBSchema just to pass in some config variables to the object.

2. Return DBSChema object from a factory. Now i would use a singleton Factory that then takes in a param ( db file path ) and maps this to a schema object. To make sure I have a singleton schema object my Factory will use a hashmap to store the dbFile path against the object. If an object exists for a certain file path then I just return the object. Now the thing I don't like about this is that I am only ever creating a single DBSchema. Its not like I have multiple types of Schema that the factory needs to return. So its a bit of a waste of a factory ( although i suppose its good for future multiple SChema's )

Thoughts on either choice will be appreciated as I can't decide???

Now for a quick Exception question

3. Say I have a singleton class that creates randomAccessFile. Should i propogate any exceptions e.g FileNotFoundException up to the calling class ( the class that calls instance() or should I deal with them in the singleton??


SCJP
Dieskun Koper
Ranch Hand

Joined: Aug 15, 2004
Posts: 85
Hello Mark,

Regarding Q3, it depends on your singleton. What does it do, what does it represent?
Look at these examples:

1.
FileAccessor class:
public getInstance(String filename) throws FileNotFoundException

2.
RecordHolder class:
public getInstance(Map connectionProperties) throws FileNotFoundException

The first case it makes sense to throw the FileNotFoundException. In the second (a more general case, the connectionProperties could contain a filename, or perhaps a provider url), a more general exception (ConnectionFailed, or an application exception) makes more sense.

I used a 3 tier approach, with each tier catching such exceptions and throwing a new application exception specific to that tier, so that I do not need to change any client code if the database is changed.

Regards,
Dies
Mark Thomson
Greenhorn

Joined: Jul 20, 2004
Posts: 15
Thanks, I reckon i will wrap the low level exceptions up in my own exceptions and propogate those up to the calling class

Now after some long and hard thinking I reckon I am going to make my Schema class a singleton rather than access via a factory. I will have a getInstance(String fileName ) method. Now i don't really like this implementation of the singleton pattern but i reckon its the safest way to go.

Does anyone have concerns about forcing a singleton to take a parameter in the getInstance method??
peter wooster
Ranch Hand

Joined: Jun 13, 2004
Posts: 1033
Originally posted by Mark Thomson:
Thanks, I reckon i will wrap the low level exceptions up in my own exceptions and propogate those up to the calling class

Now after some long and hard thinking I reckon I am going to make my Schema class a singleton rather than access via a factory. I will have a getInstance(String fileName ) method. Now i don't really like this implementation of the singleton pattern but i reckon its the safest way to go.

Does anyone have concerns about forcing a singleton to take a parameter in the getInstance method??


The getInstance method should not take a parameter, what would you do if the paramater was different on the second call to the first? If you were creating a multiton this would be acceptable, then the instances would be kept in a map keyed by the parameter. For a singleton there should only be one. If you need to initialize it the first time its called, you could fetch the file name from the properties within the private constructor. In my program the properties are also managed by a singleton, so they are easy to access.
Mark Thomson
Greenhorn

Joined: Jul 20, 2004
Posts: 15
Thanks for your reply Peter,

I know letting a singleton take a parameter is bad but I can't see how I can pass through a parameter to my singleton??

Now for the schema singleton I was thinking of using the properties file, but I don't like the idea of the app starting up for the first time, writing the dbFile location to a property file and then having the singleton read from the property file. Could have some threading issues etc.

Any ideas??
peter wooster
Ranch Hand

Joined: Jun 13, 2004
Posts: 1033
Originally posted by Mark Thomson:
Thanks for your reply Peter,

I know letting a singleton take a parameter is bad but I can't see how I can pass through a parameter to my singleton??

Now for the schema singleton I was thinking of using the properties file, but I don't like the idea of the app starting up for the first time, writing the dbFile location to a property file and then having the singleton read from the property file. Could have some threading issues etc.

Any ideas??


I use a properties singleton that loads the properties at startup, caches changes and saves the properties at shutdown. When I get a new connection to the database, I get the location from the properties singleton. The properties are stored in a Properties object, which inherits from Hashtable and is synchronized. I do have one pair of properties that could cause threading problems, the address and port. This is only set or referenced by actions that run on the Event Dispatch Thread.
Stein Skogseth
Greenhorn

Joined: Nov 08, 2004
Posts: 1
Hi all,

My first post on JavaRanch, hope I didn't miss any rules...

It seems to me you want to use a pattern (Singleton) and are looking for a place to make it fit in (a File with RandomAccess). You should really do it the other way around: Recognise a problem, use the right pattern.

And about Singletons: To quote (at least allmost, don't have the book here) Kent Beck in the book Test Driven Development: "When should you use a global variable in a language that don't support global variables? Don't! Your design will thank you." A Singleton is public, your file shold be encapsulated in your database unless you have a good reason to publish it.

And the idea of a Singleton Factory is a contradiction in terms. Either you want a Singleton aka a global variable, or you want a Factory to make objects (note the plural form).

In my assignment it's very clear where to put the db file. My bet is on hard coding its path. Anyway a parameter is a way to make a difference by being able to pass different values to a method. You probably allways want the same file, so I really don't see why you want it as a parameter.

My advice to you is to think more simple. Do what they ask, don't make the fanciest solution ever.

Stein :-)
Anton Golovin
Ranch Hand

Joined: Jul 02, 2004
Posts: 476
Hi, Mark! Hope this opinion is useful.

The Singleton pattern is the first natural choice, because it affords the guarantee that the class exists in only one instance. However, what if you wish to change the database file? Then you would still be able to implement the Singleton pattern, but with some modification. So Singleton pattern works and is simple.

The Factory pattern would return an instance of the class based on the data file. It causes a cleaner separation of responsibilities between the schema and something that changes the schema based on a parameter. So this is a better choice.


Anton Golovin (anton.golovin@gmail.com) SCJP, SCJD, SCBCD, SCWCD, OCEJWSD, SCEA/OCMJEA [JEE certs from Sun/Oracle]
Swamy Nathan
Ranch Hand

Joined: May 16, 2004
Posts: 187
Heres A question about singleton.
Why use them when you can also use a class with only static fields and static methods and get same effect?

I have my own opinion on why singleton is a good idea vs the static thing but want to hear your views on it.
Daniel Simpson
Ranch Hand

Joined: Sep 02, 2004
Posts: 181
This is in my documentation about delivery:
All configuration must be done via a GUI, and must be persistent between runs of the program. Such configuration information must be stored in a file called suncertify.properties which must be located in the current working directory.
Exactly, what do they mean by configuration via a GUI? So when my application launches in networked mode, I need to allow the user to enter the i.p. address, port, file location, etc? And when in non-networked, I need to allow the user to choose where the file location is. Am I right? Secondly what does it mean that this should be stored in a file called suncertify.properties. Doesn't that mean there is a package called suncertify.properties and not an actual file called that? And what does it mean that it should be located in the current working directory? Which current working directory would that be? So here is my take from it. Before I launch the actual gui app every time, a gui window comes up allowing the client to configure the connection etc. Then, writes all of that to a file called properties.txt. On subsequent launchings of the application, the user will have the choice of configuring (which will then overwrite the current properties file) or use the properties located in the file. If it is the first time the app is being used, the properties file will be created, otherwise it will be read or overwritten the next time the app is launched? Am I right on this speculation? Let me know! I appreciate everyone's help.


SCJP 1.4<br />SCJD 1.4
peter wooster
Ranch Hand

Joined: Jun 13, 2004
Posts: 1033
Originally posted by Swamy Nathan:
Heres A question about singleton.
Why use them when you can also use a class with only static fields and static methods and get same effect?

I have my own opinion on why singleton is a good idea vs the static thing but want to hear your views on it.


Why use a Singleton? The main reason is that a singleton is a real object, an instance of a real class. You can extend the class and you can pass the object as a parameter to a method. It's able to participate in all the aspects of Object Oriented Programming.

The singleton uses a static method to get it's instances, but doesn't expose any static variables. Take a look at the Language reference and you'll probably find more reasons to avoid non private static variables.
peter wooster
Ranch Hand

Joined: Jun 13, 2004
Posts: 1033
Originally posted by Daniel Simpson:
[QB]This is in my documentation about delivery: Exactly, what do they mean by configuration via a GUI? ...


Configuration by GUI means that you must provide a Graphic User Interface that allows the CSR a way to configure the options using familiar windows or X widgets.

The options will get stored in a Properties file called "suncertify.properties" in the current directory, this file will be managed using java.util.Properties.load() and .store(). The first time the program is run this file won't exist, but will be created using default values, any changes made to the properties will be saved (persisted) to this file either when changed or on exit.
Anton Golovin
Ranch Hand

Joined: Jul 02, 2004
Posts: 476
Hi, Peter! When might the ranchers see your project graded? Save for the opportunities to help aspiring test-takers, this is what also keeps me coming back to this forum - the interest in the outcome for people who did the project concurrently as I was doing it.

When are you submitting?
[ November 19, 2004: Message edited by: Anton Golovin ]
Daniel Simpson
Ranch Hand

Joined: Sep 02, 2004
Posts: 181
The options will get stored in a Properties file called "suncertify.properties" in the current directory, this file will be managed using java.util.Properties.load() and .store(). The first time the program is run this file won't exist, but will be created using default values, any changes made to the properties will be saved (persisted) to this file either when changed or on exit.


Thanks! I've been messing around with it, and now I understand how it works. My one question is this: what is the current directory? Or what should it be? Here is my code to make that file:

When I look in my folder. It is located outside of my suncertify package. In that folder, i have my docs folder, my suncertify package (which contains my gui, sockets, and db packages), and this properties file "suncertify.properties." Am I doing this right, or should there be a package called that? Thanks again for the help!
peter wooster
Ranch Hand

Joined: Jun 13, 2004
Posts: 1033
Originally posted by Daniel Simpson:
When I look in my folder. It is located outside of my suncertify package. In that folder, i have my docs folder, my suncertify package (which contains my gui, sockets, and db packages), and this properties file "suncertify.properties." Am I doing this right, or should there be a package called that? Thanks again for the help!


The current directory is the directory that you started java from. Or it may be changed by the program. This way if you start 2 servers from 2 different directories they will use different properties.
peter wooster
Ranch Hand

Joined: Jun 13, 2004
Posts: 1033
Originally posted by Anton Golovin:
Hi, Peter! When might the ranchers see your project graded? Save for the opportunities to help aspiring test-takers, this is what also keeps me coming back to this forum - the interest in the outcome for people who did the project concurrently as I was doing it.

When are you submitting?

[ November 19, 2004: Message edited by: Anton Golovin ]

Hi Anton,

I've gotten busy with real work, so it may be a while. I've completed coding and user documentation. I'm now reviewing the Javadoc and doing further tests.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Singleton / Factory decision