java的6种单例模式

Java105

第一种类型:Hungry Han类型:当你第一次访问这个对象时,它会像你以前没有吃过一样,所有的类都会被加载

[En]

The first type: Hungry Han type: when you first access this object, it will be like you haven't eaten before, and all classes will be loaded in

缺点:太消耗内存,全部加载不一定都会使用,产生垃圾
优点:没有加锁,速度快
java的6种单例模式

第二种:懒汉式(线程不安全)
缺点:没加锁,在多线程下会出问题。
java的6种单例模式

第三种:懒汉式(线程安全,加锁)
缺点:因为加锁了,故效率会降低
优点:节省内存。只有在进行第一次呼叫时才会创建。由于锁,它支持多线程

[En]

Advantages: save memory. It will be created only when the first call is made. Because of the lock, it supports multithreading

java的6种单例模式

第四种:双检锁
特征

[En]

Features

java的6种单例模式

第五种:静态内部类
特性:还实现了延迟加载,但不是先调用然后加载这个类。此对象仅在调用内部类时实例化。它进一步节省了内存,实现起来更简单。

[En]

Feature: lazy loading is also implemented, but it is not the case that this class is called and then loaded. This object is instantiated only when the internal class is called. It further saves memory and is simpler to implement.

输入验证码查看隐藏内容

扫描二维码关注本站微信公众号 Johngo学长
或者在微信里搜索 Johngo学长
回复 svip 获取验证码
wechat Johngo学长