Java - Why Enum Singleton are better in Java
来源:互联网 发布:穆逢春 知乎 编辑:程序博客网 时间:2024/05/18 01:46
http://javarevisited.blogspot.de/2012/07/why-enum-singleton-are-better-in-java.html
Because I can't open this page without proper proxy, so I copy the content here.
Enum Singletons are new way to implement Singleton pattern in Java by using Enum with just one instance. Though Singleton pattern in Java exists from long time Enum Singletons are relatively new concept and in practice from Java 5 onwards after introduction of Enum as keyword and feature. This article is somewhat related to my earlier post on Singleton, 10 interview questions on Singleton pattern in Java where we have discussed common questions asked on interviews about Singleton pattern and 10 Java enum examples, where we have seen how versatile enum can be. This post is about why should we use Enum as Singleton in Java, What benefit it offers compared to conventional singleton methods etc.
Following are some reasons which make sense to me for using Enum to implement Singleton pattern in Java. By the way If you like articles on design pattern than you can also check my post on Builder design pattern and Decorator design pattern .
1) Enum Singletons are easy to write
This is by far biggest advantage, if you have been writing Singletons prior ot Java 5 than you know that even with double checked locking you can have more than one instances. though that issue is fixed with Java memory model improvement and gurantee provided by volatile variables from Java 5 onwards but it still tricky to write for many beginners. compared to double checked locking with synchronization Enum singletons are cake walk. If you don't believe than just compare below code for conventional singleton with double checked locking and Enum Singletons:
Singleton using Enum in Java
This is the way we generally declare Enum Singleton , it may contain instace variable and instance method but for sake of simplicity I haven’t used any, just beware that if you are using any instance method than you need to ensure thread-safety of that method if at all it affect the state of object. By default creation of Enum instance is thread safe but any other method on Enum is programmers responsibility.
/*** Singleton pattern example using Java Enumj*/public enum EasySingleton{ INSTANCE;}
/*** Singleton pattern example with Double checked Locking*/public class DoubleCheckedLockingSingleton{ private volatile DoubleCheckedLockingSingleton INSTANCE; private DoubleCheckedLockingSingleton(){} public DoubleCheckedLockingSingleton getInstance(){ if(INSTANCE == null){ synchronized(DoubleCheckedLockingSingleton.class){ //double checking Singleton instance if(INSTANCE == null){ INSTANCE = new DoubleCheckedLockingSingleton(); } } } return INSTANCE; }}
You can call DoubleCheckedLockingSingleton.getInstance() to get access of this Singleton class.
Now Just look at amount of code needed to create a lazy loaded thread-safe Singleton. With Enum Singleton pattern you can have that in one line because creation of Enum instance is thread-safe and guranteed by JVM.
People may argue that there are better way to write Singleton instead of Double checked locking approach but every approach has there own advantages and disadvantages like I mostly prefer static field Singleton intialized during classloading as shwon in below example, but keep in mind that is not a lazy loaded Singleton:
Singleton pattern with static factory method
This is one of my favorite method to impelemnt Singleton pattern in Java, Since Singleton instance is static and final variable it initialized when class is first loaded into memeory so creation of instance is inherently thread-safe.
/*** Singleton pattern example with static factory method*/public class Singleton{ //initailzed during class loading private static final Singleton INSTANCE = new Singleton(); //to prevent creating another instance of Singleton private Singleton(){} public static Singleton getSingleton(){ return INSTANCE; }}
//readResolve to prevent another instance of Singleton private Object readResolve(){ return INSTANCE; }
- Why Enum Singleton are better in Java
- Java - Why Enum Singleton are better in Java
- Java - Why multiple inheritances are not supported in Java
- Java Enum Singleton
- Why multiple inheritances are not supported in Java
- Why character array is better than String for Storing password in Java
- Enum Types in java
- Why most large-scale Web sites are not written in Java
- java用enum实现singleton的方法
- Design Patterns in Java - Singleton
- 设计模式 - Singleton in Java
- jdbc 4 :Better SQLExceptions in Java 6
- Why Windows Threads Are Better Than POSIX Threads
- Java Enum Tutorial: 10 Examples of Enum in Java
- Why do we need Lambda in Java?
- Why Web Services are needed in Industry
- Why are all programming languages in English?
- Why are pointers used in C++?
- GRE作文备考——教育的三大目的
- STL学习笔记之前篇
- 编译android源码提示/usr/bin/jar命令不存在问题的解决方法
- gcc -rdynamic参数解释
- recommenderjob原码分析
- Java - Why Enum Singleton are better in Java
- 【HTTP】HTTP状态码
- ABAP--SAP是如何回写CL_GUI_ALV_GRID_BASE的MT_MODIFIED_CELLS的
- Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationT
- Flume NG源码分析(四)使用ExecSource从本地日志文件中收集日志
- appcompat_v7\res\values-v21\themes_base.xml:191: error: Error: No resource found that matches the gi
- ANDROID L——Material Design详解(动画篇)
- 欢迎使用CSDN-markdown编辑器
- Android程序:使用Http的Get方式读取网络数据