单例模式简介

单例模式

简介:

  • 单例模式就是一个类只有一个实例。需满足条件如下:
  1. 通过 static 关键字确保类只有唯一实例
  2. 类的构造函数需要私有化,确保外部不能调用构造函数创建实例
  3. 类通过静态方法或者静态变量为外部访问唯一实例提供入口

实现方法

饿汉模式

public class Singleton{
  private static Singleton instence = new Singleton();
  
  private Singleton(){};

  public static Singleton getInstence(){
    return instence;
  }
}

懒汉模式(非线程安全)

public class Singleton{
  private static Singleton instence = null;

  private Singleton(){};

  public static Singleton getInstence(){
  //多线程时候会出现线程安全问题,
  //因为是单例模式使用static修饰只能为一个实例
    if (instence == null){
      return new Singleton();
    }
  }
}

懒汉模式(线程安全)

public class Singleton{
  private static Singleton instence = null;

  private Singleton(){};

  public static Singleton getInstence(){
    if (instence == null){//减少锁开销,如果存在不加锁
      synchronized(Singleton.class){
        if (instence == null){//当线程1释放锁后,单例已存在,防止线程2获取锁继续创建,然后出现static修饰变量两次实例化申请空间
          return new Singleton();
        }
      }
    }
  }
}

静态内部类模式

public class Singleton{
  private Singleton(){};

  private static class SingletonHolder{
    private static Singleton instence = new Singleton();
  }

  public Static Singleton getInstence(){
    return SingletonHolder.instence;
  }
}

参考文档:单例模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值