Ideas are usually trivialized as they are popularized. Great ideas retain their essence as they go through the process. Others become empty slogans that hinder true understanding and progress.
public class Registry {
private static Registry instance;
private Registry() {
}
public synchronized static Registry getInstance() {
if (instance == null) {
instance = new Registry();
}
return instance;
}
// ...
}
How many times have you written code like this? If you answered "Every time I implement a singleton class," you are not alone.
But aren't you writing a lot of duplicated code? Whatever happened to object-orientation and code reuse?
"But, but, bu---the code it so simple. And my IDE can write it for me."
Is the above code a faithful translation of the C++ code in The Book? Are you sure?
Well, not quite. For one thing, the constructor is protected in the GoF code. And the book spent almost two pages out of the seven dedicated to the pattern talking about subclassing a singleton class.
As the singleton pattern is popularized, it is also trivialized. In this case the essence of the pattern is retained.
As an example of over trivialization, I'll cite the "partial extreme programming" phenomenon I alluded to thirty days ago, whereby the three inter-leaning principles of XP:
Do not write code without a failing test
Write the simplest code to make the tests pass
Refactor relentlessly to improve the design of the code
Is reduced to:
Write the simplest code that will work
Thus opening the gate to all sorts of irresponsible coding practices.
Today's homework: In the ACE C++ Framework, there is a template class called ACE_Singleton that adapts an ordinary class into a singleton class.
With the help of generics in J2SE 5.0, we should be able to write something similar to decouple the business logic of a class from its singleton-ness.
Doing this can save everyone from having to write the boilerplate singleton code again and again. It may also help reduce the complaint that singleton classes are hard to test.