views:

64

answers:

2

So, I want to go for a more Singleton - less design in the future. However, there seem to be a lot of tasks in an application that can't be done in meaningful way without singletons.

I call them "application wide services", but they also fall into the same category as the cross cutting concerns, which I usually fix via AOP.

Lets take an example:

I want an application wide message queue that dispatches messages to components, every component can subscribe and publish there, it's a very nice multicast thing.

The message queue and dispatching system are usually a (rather short) singleton class, which is very easy to implement in, say, C#. You can even use double dispatching and utilize message type metadata and the like, it's all so easy to do, it's almost trivial.

However, having singletons is not really "object oriented design" (it introduces global variables) and it makes testing harder.

Do you have any ideas? I'm asking this question because I'm willing to learn more about this topic, a LOT more. :-)

Edit:

I thank you all for your answers so far. I guess I have asked the wrong question, maybe it should have been "are singletons really that bad?".

It's a bit confusing... people telling you "omg singletons bad smellz!!11" all over the place - and on the other hand, they seem to be the easiest and most straightforward solution to those application - scope problems.

This is one of my "sticking points" at the moment. Solving this riddle.

+1  A: 

It's easier to understand how software works when the lifecycle of all application scope services/classes is managed in a centralized way. I like the idea of the JNDI.

In your case I would have an application wide Queue Manager instance available JNDI or an analogous service. The manager would be initialized upon the first request from the configuration provider available via the same mechanism.

In general, when you need to architect an enterprise multitier system, the J2EE is a good place to check what's already invented and being used.

bobah
+2  A: 

If you are talking about Singletons in the way that your application code does:

MessagingClass.getInstance().doStuff()

in your methods, one alternative is to use "dependency injection". Which means, use the same MessagingClass, but provide it to classes that use it via a constructor or setter when they are created.

This way, you can provide different types of your MessagingClass when in different situations.

Note, you do not need a dependency injection framework on anything of its sort to do this.

edit: the crux of dependency injection is that your code does not go around looking for classes it needs to work (dependencies), it gets them "injected" on creation. This way, the obtaining of dependencies is not mixed with the rest of your code, which seems to be very useful.

alex
I like this answer very much! :-)
StormianRootSolver