Dave wrote:
On 5/19/07, Allen Gilliland <[EMAIL PROTECTED]> wrote:
> Some objects are going to be singletons, and we can declare that, but
> I don't see the need to "enforce" it. Who are we protecting ourselves
> from? If a DI framework wants public constructors, I don't think that
> is a problem at all.

don't see the need to enforce it?  i don't understand that logic, if a
class is supposed to be a singleton then why would you not enforce it?
the whole point of a singleton is that it's supposed to allow for *only*
one instance, if you don't enforce that then someone can do the wrong
thing with your code.

Yes, I agree. Generally, it's a good thing to enforce singletons, but...


enforcing that is to protect potential Roller users who want to build on
the Roller code as a platform so that they do the right thing.

If a DI framework requires classes to have public constructors, even
those that are singletons -- you would completely rule out the usage
of that framework? I think that rules out both Spring IOC and Guice
and I'm not ready to rule out either.

I am not saying we have to rule them out, I am simply saying that from an api point of view I think it's best to truly enforce constraints such as the singleton pattern when they are critical. Truth be told, I don't think there is any real reason why many of our manager classes and even the Roller class needs to be a singleton, we mainly do that for performance reasons because there is no benefit to constructing them over and over again. So for that reason I don't think it's such a big deal to rely on Guice or any other DI framework to handle the singleton functionality for us, and I would be okay with the public constructor.

However, in situations where it's imperative that the singleton pattern be properly enforced I think it's best that we actually do so in the code both for consistency and to make the code read the way it's supposed to work. An example would be the HibernatePersistenceStrategy class, which *must* be a singleton because we don't want multiple hibernate SessionFactory instances floating around on accident. In that case I think we should abandon the public constructor and use the singleton pattern the way it's meant to be enforced. This also does not prevent us from using Guice because from the docs it says you can bind instances to classes just as easily as you bind anything else, so you could use this in the HibernateModule ...

binder.bind(HibernatePersistenceStrategy.class).toInstance(HibernatePersistenceStrategy.getInstance());

This way you are still using Guice to do your DI, however instead of using Guice to enforce the singleton patter you do it directly in the class which makes it plain for anyone reading the class that it's required to be a singleton.

-- Allen


There is some discussion of implementing singletons with straight
Java, Spring and Guice here:
http://docs.codehaus.org/display/GROOVY/Singleton+Pattern

- Dave

Reply via email to