User Tools

Site Tools


tech:design-pattern

Singleton

一般Singleton模式通常有几种种形式:

第一种形式: 定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。

public class Singleton {
 
  private Singleton(){}
 
  private static Singleton instance = new Singleton();
 
  public static Singleton getInstance() {
    return instance;
  }
 
}

第二种形式:

public class Singleton {
 
private static Singleton instance = null;
 
public static synchronized Singleton getInstance() {
 
  if (instance==null) {
    instance=new Singleton();
  return instance; 
  }
}
tech/design-pattern.txt · Last modified: 2018/07/24 08:13 by 127.0.0.1

Except where otherwise noted, content on this wiki is licensed under the following license: 沪ICP备12046235号-2
Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki