单例设计模式

单例设计模式

保证对象的不变性。在某种情况你可能需要多个地方取得同一个对象。这个时候你可以使用单例模式。

第一种方式:饿汉式 线程安全,调用效率高,但是不能延时加载。
缺点:如果你不适用这个类,他还是加载了。

public class Test{
   private static static Test test=new Test;
   
   public Test(){
   
   }
   
   public static Test getInstance(){
          return test;
   }

}

第二种方式:懒汉式 线程安全,调用效率不高,可以延时加载。

public class Test{
   private static Test test;
   
   public Test(){
   
   }
   
   public static synchronized Test getInstance(){
      if(test==null){
	     test=new Test();
	  }
      return test;
   }

}

第三种方式: 静态内部类实现模式 线程安全,调用效率高,可以延时加载

public class Test{
   private static class SingletonClassInstance{
     private static final Test test=new Test();
   }
   
   public Test(){
   
   }
   
   public static Test getInstance(){
      return SingletonClassInstance.test;
   }
}

综上给出三种单例模式设计风格,也可以看出我们使用第三种是比较好的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值