1. 程式人生 > >單例模式實現

單例模式實現

鎖定 word nal ron 單例模式 tin public 原子操作 ==

  1. 靜態內部類(static nested class) 優先考慮
  2. public class LazySingleton{
  3. private LazySingleton(){}
  4. private static class Nested{
  5. private static final LazySingleton single = new LazySingleton();
  6. }
  7. public static LazySingleton getInstance(){
  8. return Nested.single;
  9. }
  10. }

雙重檢查鎖定(DCL)

  1. public class LazySingleton{
  2. private LazySingleton(){}
  3. private static volatile LazySingleton single = null;
  4. public static LazySingleton getInstance(){
  5. if(single == null){
  6. synchronized (LazySingleton.class){
  7. if(single == null){
  8. single = new LazySingleton(); //① 非原子操作
  9. }
  10. }
  11. }
  12. return single;
  13. }
  14. }

單例模式實現