java面试题 单例设计模式

单例设计模式   

  1. 某个类必须只有一个实例 (构造器私有化)
  2. 类必须自行创建实例(含有一个该类的静态变量存储该实例)
  3. 类自行向其他类提供这个实例  (对外提供获取该实例对象的方式)

 饿汉式  

       在类初始化的时候直接创建对象  不存在线程安全问题

 

          1、直接实例化饿汉式(简洁直观)

           2、静态代码块饿汉式(适合复杂实例化)

        3、枚举式(最简洁)

 

  1 

1 public class Singleton1 {
2     public final static Singleton1 singleton = new Singleton1();
3 
4     private Singleton1() {
5 
6     }
7 }

2

1 public enum 枚举{
2    // 实例变量名
3    instance
4 }

3

public class Singleton2 {
    public final static Singleton2 INSTANCE;
    static {
        INSTANCE = new Singleton2();
    }
    private Singleton2() {
        
    }
}
public class Singleton2 {
    public final static Singleton2 INSTANCE;
private String ss static {
info =从文件中获得数据 INSTANCE = new Singleton2("info"); } private Singleton2(String s) { this.ss=s; } }
 

 

懒汉式:延迟创建对象

 4、线程不安全式(适用于单线程)

    5、双重校验式,线程安全(适用于多线程)

    6、静态内部类式(适用于多线程)

 


//线程不安全
public class s { 2 3 private static s instance; 4 private s(){} 5 6 public static s getInstance(){ 7 if (instance==null){ 8 instance=new s(); 9 } 10 return instance; 11 } 12 }
//线程安全版
public class s2{

    private s2(){}
    private static s2 instance;
    public static s2 getInsatnce(){

     if(!instance==null){
        synchronized(s2.class){
        
          if(instance==null){
           instance=new s2();
          }
        }  
     }
     return instance;
   }
}

 

 1 //在内部类被加载和初始化的时候  才创建instance实例对象
 2 //静态内部类不会随着外部类的加载和初始化而初始化   它需要单独去加载和初始化
 3 //因为是在内部类加载和初始化的时候才加载和创建的 因此是线程安全的
 4 public  class s3{
 5 
 6    private s3(){}
 7    
 8     private static class Inner{
 9         private static final s3 instance =new s3();
10    }
11 
12    public static s3 getInstance(){
13    
14     return Inner.instance; 
15   }
16 }

 



 

posted @ 2019-06-06 19:12  ikun~  阅读(908)  评论(0编辑  收藏  举报