简单易懂的单例模式

什么是单例模式?
单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

单例模式的特点?
①、单例类只能有一个实例
②、单例类必须自己创建自己的唯一实例
③、单例类必须给所有其他对象提供这一实例

单例模式的分类(饿汉和懒汉):

饿汉模式

饿汉模式:主动去找食物,一开始就吃掉。
class Singleton { 
    private static Singleton instance = new Singleton(); 
    private Singleton() {
} 
public static Singleton getInstance() { 
//getInstance是获取单例对象的方法,
    return instance; 
    } 
}

懒汉模式-等着人去喂食物(单例的初始值为空,还未构建)

懒汉模式-单线程版
public class Singleton {
    private Singleton() {}  //私有构造函数:.要想让一个类只能构建一个对象,自然不能让它随便去做new操作,因此Signleton的构造方法是私有的
    private static Singleton instance = null;  //单例对象
    //静态工厂方法
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
懒汉模式-多线程版-性能低
class Singleton {
    private static  Singleton instance = null; 
    private Singleton() {
    }
    public synchronized static Singleto getInstance() {//为了防止new Singleton被执行多次,因此在new操作之前加上Synchronized 同步锁,锁住整个类
                if(instance==null){
                instance = new Singleton();
           }
   return instance; 
   }
}
懒汉模式-多线程版-二次判断-性能高
class Singleton {
    private static volatile Singleton instance = null; 
    private Singleton() {
    }
    public  static Singleton getInstance() { 
        if (instance == null) { / //双重检测机制/
            synchronized(Singleton.class){
                if(instance==null){
                instance = new Singleton();
           }
       }
  }
   return instance; 
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值