当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
Java中单例模式的几种正确实现方法
发布时间:2010/8/30 15:39:48 来源:城市学习网 编辑:ziteng

  第一种:同步

  public class Singleton {

  private static Singleton instance;

  private Singleton() {

  }

  public synchronized static Singleton getInstance() {

  if (instance == null) {

  instance = new Singleton();

  }

  return instance;

  }

  }

  第二种:静态初始化

  public class Singleton {

  private static Singleton instance = new Singleton();

  private Singleton() {

  }

  public static Singleton getInstance() {

  return instance;

  }

  }

  第三种:静态holder类

  public class Singleton {

  private Singleton() {

  }

  private static class SingletonHolder {

  public static Singleton instance = new Singleton();

  }

  public static Singleton getInstance() {

  return SingletonHolder.instance;

  }

  }

广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved