java 单例模式

在项目中遇到了java单例模式,因此拿出来学习了一下。后来发现原来用的单例模式是“懒汉式单例模式”

public class IssueSaleService{

  private static IssueSaleService instance = null;

  public IssueSaleService(){

  }

  public static synchronized IssueSaleService getInstance(){

    if(instance == null){

      instance = new IssueSaleService();

    }

    return instance;

  } 

}

另外进行学习,“饿汉式单例模式”就是在类加载的时候不进行创建,在第一次实例化的时候进行创建。

public class IssueSaleService{

  //创建一个私有的唯一的成员,

  private static final IssueSaleService instance = new IssueSaleService();//

  //私有方法,避免外部新建实例

  private IssueSaleService(){

  }

   public static IssueSaleServcie getInstance(){

    return instance;

  }

}

其中,饿汉是线程安全的,在类创建的同事就创建一个对象供引用,以后不用关注线程问题。 懒汉必须加synchronized 修饰。

但是,饿汉存在效率问题,如果有多个这样的类,会严重影响效率,因此在项目中要考虑这个情况。

网上看到一种内部类的实现方式:

public class Test{

  static{

  }

  public static Test getInstance(){

    return TestInstance.getInstance();

  }

  private Test(){

  }

  private static class TestInstance{

  private static Test instance = new Test();

  private TestInstance(){

  }

  private static Test getInstance(){

    return instance;

  }

  }

}

posted @ 2012-01-10 10:03  庸蛹  阅读(229)  评论(0编辑  收藏  举报