Recent top five:
Java.next -- Four languages that represent the future of Java
Blogger Stuart Halloway has begun a series of posts on trends that point to the future of the Java platform. In his first
post, he compares Clojure, Groovy, JRuby, and Scala -- four wildly different languages that nonetheless all play together
in the JRE. Find out what unites these languages and what they can tell us about the future of Java-based development ...
| Enterprise AJAX - Transcend the Hype |
| Memory Analysis in Eclipse |
| Oracle Compatibility Developer's Guide |
| Memory Analysis in Eclipse |
I have seen singleton classes used in many places. My question: What is the advantage of using a singleton over a class with
static methods?
The difference between using a singleton over a class with static methods boils down to effective object-oriented design.
Singletons normally represent a cleaner approach. A class of static methods, unfortunately, breaks down to a simple list of
functions, or utilities.
You may ask, what's the problem with a list of functions?
Simple. With a list of functions you no longer perform object-oriented programming. In fact, your work easily devolves into a classic procedural program. Suddenly, objects no longer represent the focus of your program. You begin to fall into a data-centric programming mode. That is, instead of sending messages to objects that encapsulate state and behavior, you begin to call functions that act on data. Utilities lead to a clear division between behavior and data that you should never allow in an object-oriented design.
That's not to say that you should never use utilities. Object-oriented utilities do exist. There are times that you might need to treat objects as data. For example, I recently wrote a set of utilities that convert Java objects into a CORBA equivalent. It is difficult to turn those methods into a class since they really have no state. I also didn't want to embed the conversion code into the Java classes either. However, it is easy to mess it all up.
Use singletons when you want only one instance of a certain class in your system at any given time. An example could be a class that provides load-balanced access to CORBA servers. You wouldn't want two such objects, since each would have to get references to the same servers. Grabbing redundant resources would be wasteful. It is better to centralize the server access inside one instance.