码家

Web Platform, Cloud and Mobile Application Development

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
一般Singleton模式通常有几种种形式:


第一种形式

定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。
public class Singleton {
private Singleton(){}
      //在自己内部定义自己一个实例,是不是很奇怪?
      //注意这是private 只供内部调用
      private static Singleton instance = new Singleton();
      //这里提供了一个供外部访问本class的静态方法,可以直接访问  
      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;   } 

其他形式:
定义一个类,它的构造函数为private的,所有方法为static的。
一般认为第一种形式要更加安全些 

亲自运行:

public class Singleton {
 private static Singleton s;

 private Singleton() {
 };

 /**
  * Class method to access the singleton instance of the class.
  */
 public static Singleton getInstance() {
  if (s == null)
   s = new Singleton();
  return s;
 }
}

// 测试类
class singletonTest {
 public static void main(String[] args) {
  Singleton s1 = Singleton.getInstance();
  Singleton s2 = Singleton.getInstance();
  if (s1 == s2)
   System.out.println("s1 is the same instance with s2");
  else
   System.out.println("s1 is not the same instance with s2");
 }
}

http://www.ibm.com/developerworks/cn/java/designpattern/singleton/

posted on 2011-05-31 08:10  海山  阅读(145)  评论(0)    收藏  举报