• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton pattern

 
ravisha andar
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Can anybody please let me know what is the advantage of singleton pattern and in what scenario it can be used?


Suppose i create a singleton for the database connection object : What will happen if 15000 users login simultaneously ?



Please help me with this?

Thanks
 
Stephan van Hulst
Bartender
Pie
Posts: 5888
63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would you do something like that? You don't think you can have multiple connections?

Anyway, forget about singletons. You almost never have a good reason to use them. Only when dependency injection becomes incredibly cumbersome and doesn't add much flexibility. A good example is a logger.

Loggers should be available to the entire application, so it's cumbersome to use dependency injection. Also, loggers are fairly safe to use. If you use the same logger by multiple classes concurrently, and something goes wrong, it probably won't break your code, because loggers are not essential to the operation of your program. Information only goes one way, from your program to your logger.

If the information goes from the singleton candidate to the program, make it read only. An example is configuration settings, encapsulated in a single class. This may be considered a poor example, because configuration settings should probably be broken up and passed as arguments to the classes that need them. Read-only configuration settings are also not very flexible, because they require you to restart a program when you want new settings to take effect.

So really, singletons have *very* limited use.
 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ravisha andar wrote: Can anybody please let me know what is the advantage of singleton pattern and in what scenario it can be used?

The only advantage of the singleton pattern is that it was documented in the Gang of Four book, and everyone understands it.

Singletons Considered Harmful.

Don't use them. There is a long list of why they are the most over rated pattern in all of Java programming.
 
Stephan van Hulst
Bartender
Pie
Posts: 5888
63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you do for logging, Pat?
 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:What do you do for logging, Pat?

Apache's Log4j

I don't have to unit test it. but it does have bugs. And I get NPEs from it on occasion.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic