1.单例模式之饿汉式
作者:互联网
下面为两种饿汉式单例实现方式:
第一种:普通写法
package com.going.design.singleton.hungry;
/**
* Created by renxf on 2021/1/2
*/
public class HungrySingleton {
public static final HungrySingleton hungrySingleton = new HungrySingleton();
private HungrySingleton(){};
public static HungrySingleton getInstance(){
return hungrySingleton;
}
}
第二种:使用静态代码块
package com.going.design.singleton.hungry;
/**
* Created by renxf on 2021/1/2
* des:进一步优化
*/
public class HungryStaticSingleton {
public static final HungryStaticSingleton hungrySingleton;//final 防反射攻击
static {
hungrySingleton = new HungryStaticSingleton();
}
private HungryStaticSingleton(){};
public static HungryStaticSingleton getInstance(){
return hungrySingleton;
}
}
总结:
final:防止反射破坏单例
饿汉式缺点:可能会造成内存空间的浪费
标签:HungryStaticSingleton,hungrySingleton,饿汉,模式,final,static,单例,public,HungrySinglet 来源: https://blog.csdn.net/weixin_41474226/article/details/112514609