zoukankan      html  css  js  c++  java
  • Java中 单例(Singleton)的两种方式

     第一种(饿汉式单例模式):在声明变量时实例化

    public class Singleton {
    
         //静态初始化自动实例化
         private static Singleton instance = new Singleton(); 
         //无参数构造方法
         private Singleton(){}
       public static Singleton getInstance() {   return instance;     } }

    优点:在类加载初始化的时候就创建对象,调用getInstance的时候,没有同步方法,运行时性能较高。

    缺点:类加载速度慢,占用太多大的资源空间。

    第二种(懒汉式单例模式):把对象的创建放到方法里面去

    public class Singleton { 
      
    private static Singleton instance = null;
      private Singleton(){}   public static synchronized Singleton getInstance() {   if (instance == null){
          instance
    = new Singleton();

          }
    return instance;   } }   

    优点:避免了第一种方式的缺点, 同时,可以在多线程下运行安全。

    缺点:因为他使用了锁,在运行中效率慢。

    总结:

    单例模式的作用:

    保证一个类只有单一的实例,也就是说你无法通过new来创建这个类的一个新实例。

    当一个对象在程序内部只能有一个实例的时候,它可以保证我们不会重复创建,而是始终指向同一个对象。

    Singleton通过将构造方法限定为private避免了类在外部被实例化,在同一个虚拟机范围内,Singleton的唯一实例只能通过getInstance()方法访问。

    无参构造方法的作用是:

    每一个类至少要有一个构造函数,如果你自己构建了一个带有参数的构造函数而没有再显示的写出无参的构造也是可以的,不过当你尝试通过一个无参的构造函数来构建(new的方式)时,此时编译器才会报错,因为找不到这个无参的构造函数。

    也就是说当一个类你没有给他构造函数,则编译器会自动补上一个无参的,若有的话就不会,你需要显示将此无参的构造函数写出来

    拓展一点:Spring集成Swagger 开发

    原创直接参考:https://blog.csdn.net/BlackMambaProgrammer/article/details/72354007

  • 相关阅读:
    Spring IOC 容器源码分析
    OAuth协议简介
    MySQL安装步骤
    C# read and compute the code lines number of cs files based on given directory
    C# StreamWriter log batch message sync and async
    HttpClient SendAsync
    WebRequest, WebRequest.Create GetResponse() GetResponseStream()
    C# FileSystemWatcher
    Access Volumn via extern and invoke win 32 dll
    Change file readonly property File.SetAttribute and new FileInfo readonly property
  • 原文地址:https://www.cnblogs.com/boris-et/p/8629352.html
Copyright © 2011-2022 走看看