I’m currently maintaining application that I inherited from a colleague. So in one of his classes he wanted to implement singleton pattern. Somehow, he failed. I don’t know how, because singleton is one of the easiest design patterns around. So let’s start with a little bit of theory.
According to “GOF” the purpose of singleton is to restrict the instantiation of a class to one and only one object. In order to achieve this, we have to prevent others to access our constructors by declaring them private. This was his first mistake. He has a public constructor, ergo, anyone can instantiate this class.
The second step is to create a method that will return that one object. This is his implementation:
public static Client getInstance()
{
return instance;
}
What is wrong with this? Well, for one thing, he assumes that instance is not null. But there is no base for that. Because he hasn’t created it until he called init() method.
So, here is my question. How do you call init() method if you haven’t instantiated the class. And you can’t call the instance of class through getInstance() method because you haven’t started init() method. And then I saw the ugliest singleton call ever. There it was at the beginning of main() method. And it looked like this:
public static void main(String[] args)
{
Client applet = new Client();
...
}
The very thing we are trying to avoid is at the beginning of application. I will not give you the code for correct implementation of singleton. It can be found all over the Internet. Just check Wikipedia.








