EffecitveJava_当需要时采用保护性拷贝

<p class="MsoNormal" style=""><span style="" lang="EN-US"><span style=""><span style="font-family: Times New Roman;"><span style="font-size: small;">1.</span><span style='font: 7pt "Times New Roman";'> </span></span></span></span><span style=""><span style="font-size: small;">当需要时采用保护性拷贝</span></span></p>
<p class="MsoNormal" style="margin: 0cm 0cm 0pt 21pt;"><span style="font-size: small;"><span style="">当我们需要某一个类是</span><span lang="EN-US"><span style="font-family: Times New Roman;">immutable</span></span><span style="">的时候,如果我们必须对外界提供对象某个域的引用,或者必须使用外界提供的对象初始化值域,此时应该采用保护性拷贝。</span></span></p>
<p class="MsoNormal" style=""><span style="" lang="EN-US"><span style=""><span style="font-family: Times New Roman;"><span style="font-size: small;">2.</span><span style='font: 7pt "Times New Roman";'> </span></span></span></span><span style=""><span style="font-size: small;">不安全的代码:</span></span></p>
<p class="MsoNormal" style=""></p>
<p class="MsoNormal" style=""><span style=""><textarea cols="50" rows="15" name="code" class="java:showcolumns">import java.util.Date;

public class ImmutableErrorClass {
private Date file1;

private Date file2;

public ImmutableErrorClass(Date file1, Date file2) {
this.file1 = file1;
this.file2 = file2;
}

public Date getFile1() {
return file1;
}

public Date getFile2() {
return file2;
}
}</textarea></span></p>
<p class="MsoNormal" style=""><span style="" lang="EN-US"><span style=""><span style="font-family: Times New Roman;"><span style="font-size: small;">3.</span><span style='font: 7pt "Times New Roman";'> </span></span></span></span><span style=""><span style="font-size: small;">安全的代码:</span></span></p>
<p class="MsoNormal" style=""></p>
<p class="MsoNormal" style=""><span style=""><textarea cols="50" rows="15" name="code" class="java:showcolumns">public class ImmutableClass {
private Date file1;

private Date file2;

public ImmutableClass(Date file1, Date file2) {
this.file1 = new Date(file1.getTime());
this.file2 = new Date(file2.getTime());
}

public Date getFile1() {
return (Date) file1.clone();
}

public Date getFile2() {
return (Date) file2.clone();
}
}
</textarea></span></p>

<p class="MsoNormal" style=""><span style="" lang="EN-US"><span style=""><span style="font-family: Times New Roman;"><span style="font-size: small;">4.</span><span style='font: 7pt "Times New Roman";'> </span></span></span></span><span style="font-size: small;"><span style="">不能使用</span><span lang="EN-US"><span style="font-family: Times New Roman;">clone</span></span><span style="">方法进行初始化的方法是因为</span><span lang="EN-US"><span style="font-family: Times New Roman;">Date</span></span><span style="">类本身不是</span><span lang="EN-US"><span style="font-family: Times New Roman;">final</span></span><span style="">。因此如果用户传入一个邪恶目的的</span><span lang="EN-US"><span style="font-family: Times New Roman;">Date</span></span><span style="">实例时,无法起到保护目的。</span></span></p>

你可能感兴趣的:(java)