PDA

View Full Version : Singleton Pattern: Is It Necessary?


cdigs
03-21-2007, 04:14 PM
So I've gotten into the habit of wrapping my IApplicationContext with a singleton pattern and just now, I started wondering "Is this even necessary?".

So could anyone shed some light on this? I somehow came under the impression that GetContext() is an expensive call and that I really only needed on instance of the context. Skimming through the source, it seems like the ContextRegistry is already a singleton and the contextMap should already be performing some level of caching.

Is this analysis correct? Is there really nothing to gain by wrapping a singleton implementation around the IApplicationContext?

Thanks.

Mark Pollack
03-21-2007, 04:42 PM
Hi Charlie,

If you need simple singleton access then ContextRegistry will serve you just fine. It isn't an expensive call and the context is cached. The only reason to write your own is if you want some additional layers of indirection, for example take a look at the Javadoc for the Java version of this, i.e. SingletonBeanFactoryLocator (http://www.springframework.org/docs/api/org/springframework/beans/factory/access/SingletonBeanFactoryLocator.html). We felt that this was overkill and so made a 'classic' singleton.

As the warning there states 'It is the opinion of the Spring team that the use of this class and similar classes is unnecessary except (sometimes) for a small amount of glue code. Excessive usage will lead to code that is more tightly coupled, and harder to modify or test.'

You prob already know this, but the alternative is to refactor the code so that you an use standard DI and/or IApplicationContextAware (http://www.springframework.net/doc-latest/reference/html/objects.html#objects-context-applicationcontextaware) if at all possible.

Cheers,
Mark

cdigs
03-21-2007, 04:59 PM
Thanks for the info Mark.