Single模式

来源:互联网 发布:异界全能程序员 编辑:程序博客网 时间:2024/05/17 22:48

one:

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

two:

public class Singleton {

private Singleton(){

}
  private static Singleton instance = null;
  public static synchronized Singleton getInstance() {
    if (instance==null)
      instance=new Singleton();
    return instance;
  }
}

这两个区别在于

one: 实例的生成在类加载的时候,没有同步
two: 实例的生成在第一次访问静态方法的时候 ,有同步

原创粉丝点击