Inner class tips

写了好几年的程序的人不见得全部对语言基础都非常了解

比如说Java的内部类,除了在些框架里提供的之如spring里的callback以及GUI里面的常用匿名内部类,至少我个人很少在其他地方利用到,正好不忙,把这块部分好好补一补。

下面是总结的一些tips:

1.static inner class.

用法一:用于改进的singleton类(created by Jeremy Manson and Brian Goetz)
the Initialization on Demand Holder (IODH) idiom which requires very little code and has zero synchronization overhead. Zero, as in even faster than volatile. IODH requires the same number of lines of code as plain old synchronization, and it's faster than DCL.

java 代码
  1. public class Something   
  2.  {   
  3.      private Something()    
  4.      {   
  5.      }   
  6.         
  7.      private static class LazyHolder    
  8.      {   
  9.          private static final Something something = new Something();   
  10.      }   
  11.         
  12.      public static Something getInstance()   
  13.      {   
  14.          return LazyHolder.something;   
  15.      }   
  16.  }   

延伸阅读
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#dcl JSR 133 (Java Memory Model) FAQ
http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

用法二:懒人的测试工具
http://www.javaworld.com/javaworld/javatips/jw-javatip106.html
因为内部类编译成OutClass$InnerClass.class,所以可以在dev,test环境上保留这个类,在prod环境上不打包这个类。

所以可以在innerClass写些测试方法用来简单的单元测试,不过对于职业程序员来说还是要保持用好Junit 的习惯。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值