This week blog post is about Java Singleton design pattern. The reasons for Singleton pattern are to restricts the instantiation of a class and ensures that only one instance of the class exists. This article explains and show examples of the many different approaches of Singleton pattern implementation, the problems with the approach.
The approaches of Singleton pattern implementation:
- Eager initialization – pros: easiest way to create a singleton class | cons: instance variable is created even though it might not be used.
- Static block initialization – Similar to eager initialization but provides option for exception handling.
- Lazy initialization – This is the approach that was we used in class and it’s a completely fine for a single threaded environment, but potential can cause problems for a multi-threaded environment.
- Thread Safe Singleton – resolutions for Lazy initialization but reduces performance. Requires synchronization.
- Bill Pugh Singleton implementation – Best method for singleton implementation. Contains a inner static helper class by doing so the instance is not created unless someone calls on the getInstance() method. Doesn’t require synchronization.
- Using Reflection to destroy Singleton Pattern – This approach destroyed the singleton pattern.
- Enum Singleton – resolution for reflection method. Not flexible. Any enum value is instantiated only once.
- Serialization and Singleton – Use to store it in file system to retrieve it later. Cons: when deserialize it creates a new instance of the class.
I found this article very helpful with understanding Singleton design. This article explains to me when to use and the consequences that comes with each different implementation. The content of this blog was the best. The example code of this article was very clear and made easier to understand the materials. This change my way of using this method because I now know which method to choose in certain situation. The lazy initialization will be used more while I’m in school, but I think Bill Pugh method will be used more in the future because it’s very popular and it’s easy to understand. I agree with all the contents, but I read the comments of the other readers and they had some issue with some of the content which I have to read more about the subject to find out what’s right and wrong.