栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么要在不可变类内的吸气剂中制作防御性副本?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么要在不可变类内的吸气剂中制作防御性副本?

我相信这种情况可以证明以下说法是正确的:

public class Immutable {    private final String name;    private Date dateOfBirth;    public Immutable(String name, Date dateOfBirth) {        this.name = name;        this.dateOfBirth = dateOfBirth;    }    public String getName() {        return name;    }    public Date getDateOfBirth() {        return dateOfBirth;    }}

getName()
很好,因为它也返回不可变的对象。但是,该
getDateOfBirth()
方法可以打破不变性,因为客户端代码可以修改返回的对象,因此也可以修改对象
Immutable

Immutable imm = new Immutable("John", new Date());imm.getName(); //safeDate dateOfBirth = imm.getDateOfBirth();//hundreds of lines laterdateOfBirth.setTime(0);  //we just modified `imm` object

返回不可变的对象和基元是安全的(因为它们是通过值返回的)。但是,您需要制作可变对象的防御性副本,例如

Date

public Date getDateOfBirth() {    return new Date(dateOfBirth.getTime());}

并将集合包装在不可变的视图中(如果它们是可变的),例如,请参见

Collections.unmodifiableList()

public List<Integer> getSomeIds() {    return Collections.unmodifiableList(someIds);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437953.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号