Java: A platform for platforms
Sun's reorg may seem promising to shareholders but it's also a scramble for position. The question now is whether Sun can, or wants to, maintain its hold on Java technology. Especially with enterprise leaders like SpringSource and RedHat investing heavily in Java's future as a platform for platforms

Also see:

Discuss: Java: A platform for platforms?

Featured Whitepapers
Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Singletons rule

Keep on the object-oriented track with singletons

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Q 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?

a 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.

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.

Singletons

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.

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comment
Login
Forgot your account info?
Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources