Posted By:
Ryan_Breidenbach
Posted On:
Wednesday, June 27, 2001 10:03 AM
In Java, there really is not a big differnce between the two. Even Sun waffled on picking one over the other. Both the
System and
Runtime classes need to have exactly one instance, but the
System class uses all static methods while the
Runtime class behaves like a Singleton.
One difference is that if you need exactly one instance of a class and you want that class to implenent an interface, you must use a Singleton since interfaces cannot have static methods. Another difference is that using the Singleton pattern allows you to control exactly how many instances of a class get created, allowing you to create exactly five or exactly two instances of class if that is what you want. However, this can also be accomplished by using the Factory Method pattern, but that is another topic...
As for performance, neither will have resources allocated to them unless/until they are used. The Singleton's instance will not be created (presumably) until the getInstance method is called. The all-static class will not be loaded until one of its methods is called.
Finally, this pattern is not nearly as useful in Java as it is in other OO languages. For example, I believe that in SmallTalk, all methods must belong to an object, so Singleton's are necessary to create exactly one instance when needed. In Java, as we know, we can circumvent this by creating a class with all static methods and attributes.
Hope this helps.