Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton with DAO ?  RSS feed

 
Engin Okucu
Ranch Hand
Posts: 174
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.What 's the utility to have a singleton with DAO ?
2.Why in the factory class, i return "MyClassDAO.getInstance();"
and not "new MyClassDAO" ?
3. Why doesn't the client call directly new MyClassDAO() and we have to do something like this (by a factory class) : FactoryDAO ?
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Not sure I understand your question
2. Because you want to get an handle on the instance of a singleton, not an instance. If you return a new instance from your getInstance() method you'll quickly have more than one instance of the Singleton.
3. For the same reason as above. If you let any other object randomly create new instances of an object how do you then guarentee that there will only be one instance of that object? Basically you can't. So you control the object creation inside the object - hence a private constructor and a getInstance() method.
 
Engin Okucu
Ranch Hand
Posts: 174
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul thank you.
if i understand then, we use the singleton so that we will be sure that we will have an instance that will be accessed by ONLY one thread at a time for the transaction ? If we did use many instances of the class that handles the transaction, it will go wrong? is right ?is it the purpose ?
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. The purpose of a singleton is to provide an object which you know there is only one instance of (one instance per JVM that is). Typically you'd use this if you had a cache of data and you want to make sure the wasn't old/out of date/more than one version of the data in your application. A typical example of where you would use on in an application is if you have some unchanging configuration data stored somewhere - you can either read this in each time you need it, or read it in once and cache it in a singleton.

And since you've posted this in the EJB forum, you have to remember the EJB limitations on static data. If you use a singleton in an EJB environment it must be read only.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!