views:

75

answers:

2

I seek a solution to the age-old problem of managing string resources. My current implementation seems to work well, but it depends on using singletons, and I know how often singletons can be maligned.

The resource manager class has a singleton instance that handles lookups in the ResourceBundle, and you use it like so:

MessageResources mr = MessageResources.getMessageResources(); // returns singleton instance
...
JLabel helloLabel = new JLabel(mr.getString("label.hello"));

Is this an appropriate use of a singleton? Is there some better, more universally used approach that I'm not aware of?

I understand that this is probably a bit subjective, but any feedback I can get would be appreciated. I'd rather find out early on that I'm doing it wrong than later on in the process.

Thanks!

+1  A: 

This seems fine to me. Using a singleton is not a bad thing when it makes sense, like in this case where it provides access to some resource. Using a singleton can become a problem when you want to modify the underlying implementation of the singleton, because in most cases the access to the singleton is tied to its implementation. In your example, do you ever want to use a different implementation of the MessageResources class? Probably not, since it does its job just fine.

killdash10
+3  A: 

When you have something as ubiquitous as your MessageResources, then making it a singleton can be forgivable. But you are right to avoid them if you can.

The real question is: will this cause you a problem? Usually singletons really cause headaches in unit testing; especially if what you're passing in is an interface that you'd rather stub in the unit test code. (You are coding to interfaces, aren't you ;-)

The best alternative that I've found is dependency injection. You can either inject your dependencies manually, or use a framework like Spring or Guice.

My guess is that you have a single concrete implementation of MessageResources that works fine in unit-test land. If so, singleton may be fine. But if you find yourself writing tests that need stub/mock versions of MessageResources, you'll wish you had gone down a different path.

dave