文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>effective java: item 24: make defensive copies when...

effective java: item 24: make defensive copies when...

时间:2010-08-17  来源:llmlx

// Broken "immutable" time period class public final class Period { private final Date start; private final Date end; /** * @param start the beginning of the period. * @param end the end of the period; must not precede start. * @throws IllegalArgumentException if start is after end. * @throws NullPointerException if start or end is null. */ public Period(Date start, Date end) { if (start.compareTo(end) > 0) throw new IllegalArgumentException(start + " after " + end); this.start = start; this.end = end; } public Date start() { return start; } public Date end() { return end; } ... // Remainder omitted }  

但是这种方式会导致在如下情况下不知不觉地改变Period中end的值。这可能是我们不愿意的。

// Attack the internals of a Period instance Date start = new Date(); Date end = new Date(); Period p = new Period(start, end); end.setYear(78); // Modifies internals of p!  

因此我们要才用如下防御性的复制(defensive copy)方法

// Repaired constructor - makes defensive copies of parameters public Period(Date start, Date end) { this.start = new Date(start.getTime()); this.end = new Date(end.getTime()); if (this.start.compareTo(this.end) > 0) throw new IllegalArgumentException(start +" after "+ end); }  

而在Flex当中我们会发现ArrayCollection的一个问题就是因为没有采用防御性地复制,如var array:Array = ["1", "2", "3"]; var dp:ArrayCollection = new ArrayCollection(array); dp.addItem("4"); //Fail, array.length==4, ["1", "2", "3", "4"] Assert.assertEquals(3, array.length);  

防御性复制的另一个相关问题还体现在get方法当中,如下

// Second attack on the internals of a Period instance Date start = new Date(); Date end = new Date(); Period p = new Period(start, end); p.end().setYear(78); // Modifies internals of p!  

解决方法就是

// Repaired accessors - make defensive copies of internal fields public Date start() { return (Date) start.clone(); } public Date end() { return (Date) end.clone(); }  

在这里为什么用clone而不是前面用new Date(time)构造函数,因为前面如果用clone的话,不能确定返回值一定是Date类型,注意clone的返回值是Object,而这里用clone是因为我们明确知道它是Date类型了,其返回值肯定也是Date了。

还有一点很有意思的是,考虑到这种get会影响到类的muttable性质,所以Date.getTime返回的不是Date类型,而是long,这样就强迫你自己利用构造函数new Date(long time)来生成新的Date。

Effective Java原来还是有些东西是没有注意的。再看看。

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载