黑马程序员技术交流社区

标题: 单例设计模式的第三种实现方式 [打印本页]

作者: 班凤飞    时间: 2015-3-1 08:35
标题: 单例设计模式的第三种实现方式
视频里面毕姥爷只讲了懒汉式和饿汉式两种,还有一种双重锁模式,这个会在下面的考试里面考吗

作者: Ansel    时间: 2015-3-1 09:44
用synchronized是为了解决懒汉式的缺点,跟后面的多线程有关。都掌握了就行了。
作者: 小泽    时间: 2015-3-1 09:54
那个也是懒汉式,不过就是用在多线程中的线程安全的懒汉式。
作者: alvis2015    时间: 2015-3-1 10:04
  1. /**
  2. * 饿汉式
  3. * @author Administrator
  4. *
  5. */
  6. class EagerSingleton {
  7.         private static EagerSingleton instance = new EagerSingleton();
  8.         private EagerSingleton(){}
  9.        
  10.         public EagerSingleton getInstance(){
  11.                 return instance;
  12.         }
  13. }

  14. /**
  15. * 线程不安全的饱汉式
  16. */
  17. class LazySingleton{
  18.         private static LazySingleton instance;
  19.         private LazySingleton(){}
  20.         public LazySingleton getInstance(){
  21.                 if(instance == null){
  22.                         instance = new  LazySingleton();
  23.                 }
  24.                 return instance;
  25.         }
  26. }
  27. /**
  28.   * 线程安全的饱汉式
  29.   * 即双重锁判定模式
  30.   */

  31. class LockSingleton{
  32.          private static LockSingleton instance;
  33.          private LockSingleton(){}
  34.          public LockSingleton getInstance(){
  35.                 if (instance == null) {
  36.                         synchronized (LockSingleton.class) {
  37.                                 if (instance == null) {
  38.                                         instance = new LockSingleton();
  39.                                 }
  40.                         }
  41.                 }       
  42.                  return instance;
  43.          }
  44. }
  45. /**
  46. * 线程安全的单例模式二
  47. */
  48. class SafeSingleton{
  49.          private static SafeSingleton instance;
  50.          private SafeSingleton(){}
  51.          public synchronized SafeSingleton getInstance(){
  52.                  if(instance == null){
  53.                          instance = new SafeSingleton();
  54.                  }
  55.                  return instance;
  56.          }
  57. }

  58. /**
  59.   * 只有一个枚举值的枚举也可以用作单例模式
  60.   */
  61. enum EnumSingleton{
  62.         INSTANCE {
  63.                 @Override
  64.                 protected void someMethod() {
  65.                         // TODO Auto-generated method stub
  66.                         //需要实现的代码
  67.                 }
  68.         };
  69.        
  70.         protected abstract void someMethod();
  71. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2