views:

56

answers:

3

I am building a tool. I have a Collection Class that stores data gathered from files on network. (Why? because reading from network files was more time consuming than reading all data at once and storing data into an object) I need to use the same instance in various different classes.
I looked over the pro's and con's of Singleton Classes, and decided to use it since I felt passing around a serialized object of my Collection Class was not a good idea.

Is this a good programming technique? or is there a better solution. I can provide more details if I am not being clear

Thanks,
- Ivar
P.S: I am not sure if this has been already asked on SO, please guide me to the right post if Yes.

+1  A: 

Singleton is not a bad pattern when it is the desired behavior. However, you should not implement Singleton in the class itself.

Rather, use an Inversion of Control framework like Guice. Then, the consumer of your class can determine its lifecycle (whether it's singleton or not).

ripper234
+1 for pointing out the difference between **static** singletons and singletons as a lifecycle
Willi
+3  A: 

It depends on what your singleton does. I'll assume that our singleton gathers up files for some reason and then performs some sort of aggregation on them. If that's the case, singleton migh be an OK idea.

If you're using the singleton as a cache, that could make sense as well assuming the singleton object is the object responsible for maintaining the cache. Since I don't know your platform, I can't tell you to use an specific cache manager instead...

That being said, singletons are often an overused programming construct, and you should be somewhat wary of them. When making a decision about whether or kit to use one, ask yourself if the singleton manages a single constrained resource of some type. That's usually the only reason I find myself using them.

It's just about impossible to tell you I the desgn makes sense, though, I we don't know what happens to the data and how it's supposed to happen.

Dave Markle
i guess this is the best argument that i can get. my platform is C# and my Collection Class performs a cache after aggregation of data read from the files.- Ivar
topgun_ivard
A: 

Hi topgun_ivard!

I think it is a good option to construct a Singleton Class, this way all the other classes will be sharing the same instance and you will avoid duplication and the need to pass around the data collected.

I have two questions for you:

  1. Do you know how big/heavy your class could become? Since it will collect data, it can become really heavy.

  2. When the application closes, will you need to persist the collected data into a DB or some kind of cache?

jdecuyper
The data collected is certainly very heavy. And no, I don't need to persist data since it pertains to only one live session per user.- Ivar
topgun_ivard