面试题复习

写出几种单例模式

懒汉式-静态内部类

public  class  test {

  /**
   私有改造方法
  **/
   private  test(){
   }
   /**
   内部静态类
   **/
  private  static  class  testTwo{
    private  static final  test  testOne=new test();
  }
    public static test  getTest(){
     return testTwo.testOne;
    }
}

懒汉式-双重检查

public class test{
   private test(){
   }
   private static volatile test  testOne;
   
   public static test  getTest(){
      if(testOne == null){
        synchronized(test.class){
        if(testOne == null){
          testOne=new test();
        }
        }
      }
      return  testOne;
   }
}

饿汉式-静态变量

public class test{

private  test(){}

private static test  testOne=new test();

public static test getTest(){
return testOne;
}
}

饿汉式-静态代码块

public class test{

private  test(){}

private static test  testOne;

static{
testOne =new test()
}

public static test getTest(){
return testOne;
}
}

饿汉式-枚举

public enum test{
  testOne;
}

你可能感兴趣的:(单例模式,java)