Inner class tips JavaSpring单元测试junit框架
写了好几年的程序的人不见得全部对语言基础都非常了解
比如说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.
- public class Something
- {
- private Something()
- {
- }
- private static class LazyHolder
- {
- private static final Something something = new Something();
- }
- public static Something getInstance()
- {
- return LazyHolder.something;
- }
- }
延伸阅读
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 的习惯。