-
Code
1 // 饿汉式 2 public class Singleton{ 3 private Singleton(){} 4 private static final Singleton instance = new Singleton(); 5 public static Singleton getInstance(){ 6 return instance ; 7 } 8 } 9 // 静态代码块 10 public class Singleton { 11 private Singleton instance = null; 12 static { 13 instance = new Singleton(); 14 } 15 private Singleton (){} 16 public static Singleton getInstance() { 17 return this.instance; 18 } 19 } 20 21 // 懒汉式 在getInstance方法上加同步 22 public class Singleton { 23 private Singleton() {} 24 private static Singleton single=null; 25 public static synchronized Singleton getInstance() { 26 if (single == null) { 27 single = new Singleton(); 28 } 29 return single; 30 } 31 } 32 // 懒汉式 双重检查锁定 33 public class Singleton { 34 private Singleton() {} 35 private static Singleton single=null; 36 public static Singleton getInstance() { 37 if (singleton == null) { 38 synchronized (Singleton.class) { 39 if (singleton == null) { 40 singleton = new Singleton(); 41 } 42 } 43 } 44 return singleton; 45 } 46 } 47 // 静态内部类 48 public class Singleton { 49 private static class LazyHolder { 50 private static final Singleton INSTANCE = new Singleton(); 51 } 52 private Singleton (){} 53 public static final Singleton getInstance() { 54 return LazyHolder.INSTANCE; 55 } 56 }
参考:
http://www.blogjava.net/kenzhh/archive/2013/03/15/357824.html
时间: 2024-10-10 17:22:14