A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 班凤飞 中级黑马   /  2015-3-1 08:35  /  739 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

视频里面毕姥爷只讲了懒汉式和饿汉式两种,还有一种双重锁模式,这个会在下面的考试里面考吗

3 个回复

倒序浏览
用synchronized是为了解决懒汉式的缺点,跟后面的多线程有关。都掌握了就行了。
回复 使用道具 举报
那个也是懒汉式,不过就是用在多线程中的线程安全的懒汉式。
回复 使用道具 举报
  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. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马