单例模式
单例模式要实现的目标就是让类在内存中只能有唯一的一个实例。
要做到这一点,必须让外部不能随意的实例化此类,而将控制权掌握在类本身,对外提供一个引用供外部调用。
1.将构造函数的访问控制设为私有,这样该类的实例化就只能在类的内部进行。
2.提供一个静态的引用,将实例化的对象赋值给它。
3.提供一个静态的方法,供外部调用,获取这个引用。
代码示例:
1.非线程安全的单例类:
1 package Singleton; 2 3 public class Singleton { 4 5 private Singleton(){ 6 7 } 8 9 private static Singleton instance; 10 11 private static int counter; 12 13 public static Singleton getInstance(){ 14 if(instance == null){ 15 instance = new Singleton(); 16 counter++; 17 } 18 return instance; 19 } 20 21 /* 22 public void speak(){ 23 System.out.println("hello "+counter); 24 } 25 26 27 public static void main(String[] args) { 28 final int num = 10; 29 MyThread mt = new MyThread(); 30 Thread[] t = new Thread[num]; 31 for(int i=0;i<num;i++){ 32 t[i] = new Thread(mt); 33 } 34 for(int i=0;i<num;i++){ 35 t[i].start(); 36 } 37 38 } 39 */ 40 } 41 42 /* 43 class MyThread implements Runnable{ 44 45 @Override 46 public void run() { 47 while(true){ 48 Singleton.getInstance().speak(); 49 try { 50 Thread.sleep(1000); 51 } catch (InterruptedException e) { 52 e.printStackTrace(); 53 } 54 } 55 } 56 57 } 58 */
2.线程安全的单例类:
-
1 package Singleton; 2 3 public class Singleton2 { 4 private static Singleton2 instance = new Singleton2(); 5 6 private Singleton2(){ 7 8 } 9 10 public static Singleton2 getInstance(){ 11 return instance; 12 } 13 }
- 使用synchronized关键字
1 package Singleton; 2 3 public class AsyncSingleton { 4 private static AsyncSingleton instance; 5 6 private AsyncSingleton(){ 7 8 } 9 10 public static synchronized AsyncSingleton getInstance(){ 11 if(instance == null){ 12 instance = new AsyncSingleton(); 13 } 14 return instance; 15 } 16 }
- 双重保险
1 package Singleton; 2 3 public class EffectiveSingleton { 4 private static EffectiveSingleton instance; 5 6 private EffectiveSingleton(){ 7 8 } 9 10 public static EffectiveSingleton getInstance(){ 11 if(instance == null){ 12 synchronized (EffectiveSingleton.class) { 13 if(instance == null){ 14 instance = new EffectiveSingleton(); 15 } 16 } 17 } 18 return instance; 19 } 20 21 22 }

浙公网安备 33010602011771号