单例模式:
分析:
1、单例模式,从字面意思上理解,“单例”,即只有唯一一个实例,通常情况下,定义一个类,然后通过new ClassName()方式来产生具体对象,然而这样,破坏了一个类只有一个实例,怎么处理该问题呢?将类的具体化放在类的构造函数来完成。
2、如上方式解决了单例问题,然而,外界如何才能访问该类?很简单,该类提供一个全局的访问点即可。
3、根据以上1,2步骤的划分,单例模式有2个很明显特点:(1)类只有一个实例 (2)类必须提供全局唯一的可被访问点。
Code:
注释:如下源码引用 http://cantellow.iteye.com/blog/838473 后期,我会结合c++/java作深入分析,现阶段只是初步扫盲。
第一种(懒汉,线程不安全):
public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
第二种(懒汉,线程安全):
public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
第三种(饿汉):
1 public class Singleton { 2 private static Singleton instance = new Singleton(); 3 private Singleton (){} 4 public static Singleton getInstance() { 5 return instance; 6 } 7 }
第四种(饿汉,变种):
public class Singleton { private Singleton instance = null; static { instance = new Singleton(); } private Singleton (){} public static Singleton getInstance() { return this.instance; } }
第五种(静态内部类):
1 public class Singleton { 2 private static class SingletonHolder { 3 private static final Singleton INSTANCE = new Singleton(); 4 } 5 private Singleton (){} 6 public static final Singleton getInstance() { 7 return SingletonHolder.INSTANCE; 8 } 9 }
第六种(枚举):
1 public enum Singleton { 2 INSTANCE; 3 public void whateverMethod() { 4 } 5 }
第七种(双重校验锁):
1 public class Singleton { 2 private volatile static Singleton singleton; 3 private Singleton (){} 4 public static Singleton getSingleton() { 5 if (singleton == null) { 6 synchronized (Singleton.class) { 7 if (singleton == null) { 8 singleton = new Singleton(); 9 } 10 } 11 } 12 return singleton; 13 } 14 }
时间: 2024-11-05 18:47:03