《Core Java 2》读书笔记(二)
1,防御性编程。必要时应当考虑采取保护性拷贝的手段来保护内部的私有数据,先来看下面这个例子: 复制代码 pubic final class Period { private final Date start; private final Date end; 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 getStart() { return start; } public Date getEnd() { return end; } } 复制代码 这个类存在两个不安全的地方,首先来看第一个攻击代码 Date start = new Date(); Date end = new Date(); Period p = new Period(start, end); end.setYear(78);//改变p的内部数据! 这是因为外部和内部引用了同样的数据,为了解决这个问题,应当修改Period的构造函数: 复制代码 public Period(Date start, Date end) { this.start = new Date(start.getTime()); this.end = new Date(end.getTime()); if (start.compareTo(end) > 0) throw new IllegalArgumentException(start + "after " + end); } 复制代码 这样内部的私有数据就与外部对象指向不同,则不会被外部改变 再来看第二个攻击代码: Date start = new Date(); Date end = new Date(); Period p = new Period(start, end); p.getEnd().setYear(78);//改变p的内部数据! 这很显然是由于公有方法暴露了内部私有数据,我们可以只返回内部私有数据的只读版本(即其一份拷贝) 复制代码 public Date getStart() { return (Date)start.clone(); } public Date getEnd() { return (Date)end.clone(); } 复制代码 2,读到上面这个例子,我想起来了下面这样的代码片段 复制代码 public class Suit { private final String name; private static int nextOrdinal = 0; private final int ordinal = nextOrdinal++; private Suit(String name) { this.name = name; } public String toString() { return name; } public int compareTo(Object o) { return o } public static final Suit CLUBS = new Suit("Clubs"); public static final Suit DIAMONDS = new Suit("diamonds"); public static final Suit HEARTS = new Suit("hearts"); public static final Suit SPADES = new Suit("spades"); private static final Suit[] PRIVATE_VALUES = {CLUBS,DIAMONDS,HEARTS,SPADES}; public static final List VALUES = Collections.unmodifiedList(Arrays.asList(PRIVATE_VALUES)); } 复制代码 本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2009/09/28/1575645.html,如需转载请自行联系原作者