單例模式實現
阿新 • • 發佈:2017-09-06
鎖定 word nal ron 單例模式 tin public 原子操作 ==
- 靜態內部類(static nested class) 優先考慮
- public class LazySingleton{
- private LazySingleton(){}
- private static class Nested{
- private static final LazySingleton single = new LazySingleton();
- }
- public static LazySingleton getInstance(){
- return Nested.single;
- }
- }
雙重檢查鎖定(DCL)
- public class LazySingleton{
- private LazySingleton(){}
- private static volatile LazySingleton single = null;
- public static LazySingleton getInstance(){
- if(single == null){
- synchronized (LazySingleton.class){
- if(single == null){
- single = new LazySingleton(); //① 非原子操作
- }
- }
- }
- return single;
- }
- }
單例模式實現