单例模式的要素:
1.私有的静态的实例对象
2.私有的构造函数(保证在该类外部,无法通过new的方式来创建对象实例)
3.公有的、静态的、访问该实例对象的方法

1.饿汉模式:

public class Singleton1 {  
      
    private static Singleton1 singleton = new Singleton1();  
      
    private Singleton1(){  
          
    }  
      
    public static Singleton1 getInstance(){  
        return singleton;  
    } 
} 

   优点:线程安全、绝对单例.

  缺点:在多实例或者有其他静态方法时,在启动时没有使用它的时候就已经加载好了,浪费内存。

 

2.懒汉模式:

public class Singleton2 {  
  
    private static Singleton2 singleton;  
      
    private Singleton2(){  
          
    }  
      
    public static synchronized Singleton2 getInstance(){  
        if(singleton == null)   
            singleton = new Singleton2();  
        return singleton;  
    }  
}  

  优点:在没有使用时不用加载,节省内存。

    缺点:线程不安全,能防止反序列化、反射产生新的实例。

 

相关文章:

  • 2022-12-23
  • 2021-06-29
  • 2021-07-24
  • 2022-12-23
  • 2021-08-27
  • 2022-02-13
  • 2021-09-17
  • 2022-12-23
猜你喜欢
  • 2021-07-17
  • 2021-07-05
  • 2022-12-23
  • 2021-05-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案