Welcome

首页 / 软件开发 / 数据结构与算法 / hand first设计模式 - 单例模式

hand first设计模式 - 单例模式2012-01-05 javaeye pan_java单例模式 确保一个类只有一个实例,并提供一个全局访问点.

Java代码

public class Test {   private static Test test = null;   private Test() {   }   public static Test getInstance() {            if (test == null) {   test = new Test();  }  return test;  }  }
上面单例模式代码,采用延迟加载,在需要的时候再生成实例.但是多线程的情况可能会产生去多个实例.

Java代码

      //多线程同时访问下面代码.会产生多个实例       public static Test getInstance() {     if (test == null) {   test = new Test();  }  return test;  }