Java 4种单例

//饿汉单例,不适合大对象构建,适合小对象频繁用,用了这个类就会加载类的单例

class Singleton01{
private Singleton01(){}
private static Singleton01 instance =new Singleton01();
public static Singleton01 getInstance(){
return instance;
}
static void s(){};
}


//懒汉单例,适合大对象,稀少用

class Singleton02{
private Singleton02(){}
private static Singleton02 instance;
public static Singleton02 getInstance (){
if(instance==null){
synchronized (Singleton02.class) {
if(instance==null){
instance=new Singleton02();
}
}
}
return instance;
}}


//改进单例

class Singleton03{
private Singleton03(){}
private static class InnerSingle{
public static Singleton03 instance=new Singleton03();
}
//懒加载,利用了内部类的特点使用时才加载,何时使用何时加载,不用不加载
public static Singleton03 getInstance(){
return InnerSingle.instance;
}
}


//枚举单例,调用show方法  Singleton04.instance.show()实现单例

enum Singleton04{
INSTANCE;//枚举类的对象
public void show(){
System.out.println("show()");
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值