熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

Java中單例模式的幾種正確實現方法

2022-06-13   來源: Java高級技術 

  第一種同步

  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 SingletonHolderinstance;

  }

  }


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27588.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.