设计模式-singleton单例设计模式

文章目录

定义

保证一个类仅有一个实例,并提供一个访问它的全局访问点。

使用方式

  1. 不允许其他程序用new 创建对象。
  2. 在类中创建一个本类实例。
  3. 对外提供一个方法让其他程序获取该对象

代码

  1. 懒汉式
    调用方法时,才会建立对象,延迟加载,线程不安全。
public class Singleton {
      private  static   Singleton s=null;
      private  Singleton(){
      }
      public static Singleton getInstance(){
          if (s==null)
              s=new Singleton();
          return  s;
      }
}

线程安全的

public class Singleton {
      private  static   Singleton s=null;
      private  Singleton(){
      }
      public  static Singleton getInstance(){
          if (s==null){//如果不为null,不用重复判断锁
           synchronized (Singleton.class) {
               if (s == null)
                   s = new Singleton();
           }
          }
          return  s;
      }
}

2.饿汉式
类一加载,对象就建立了

public class Singleton {
      private  static   Singleton s=new Singleton();
      private  Singleton(){
      }
      public static Singleton getInstance(){
          return  s;
      }
}

猜你喜欢

转载自blog.csdn.net/weixin_41707267/article/details/85203070