在 Vaughn Vernon 的《实现领域驱动设计》一书中,在值对象的测试部分,作者讨论了如何使用浅复制而不是深复制来测试对象的可变性。
这是BusinessPriority的构造函数
public final class BusinessPriority implements Serializable {
private static final long serialVersionUID = 1L;
private BusinessPriorityRatings ratings;
public BusinessPriority(BusinessPriorityRatings aRatings) {
super();
this.setRatings(aRatings);
}
public BusinessPriority(BusinessPriority aBusinessPriority) {
this(aBusinessPriority.ratings());
}
这是测试用例
public void testCostPercentageCalculation() throws Exception {
BusinessPriority businessPriority = new BusinessPriority(
new BusinessPriorityRatings(2, 4, 1, 1));
BusinessPriority businessPriorityCopy =
new BusinessPriority(businessPriority);
assertEquals(businessPriority, businessPriorityCopy);
BusinessPriorityTotals totals = new BusinessPriorityTotals(53, 49, 53 + 49, 37, 33);
float cost = businessPriority.costPercentage(totals);
assertEquals(this.oneDecimal().format(cost), "2.7");
assertEquals(businessPriority, businessPriorityCopy);
}
正如我所见,在这种情况下,浅复制是不够的,因为浅复制会让businessPriority. rating()和businessPriorityCopy. rating()引用同一个对象,因此无论该对象的某些属性是否改变,它们总是相等的或不
那么我是否正确?如果是,那么为什么本书在这种情况下谈论浅复制?
//////////////////////
因为他测试的不是评级的相等性,而是测试持有评级的价值对象。
因为它们按值(而不是引用)相等,将值对象视为 java 17 记录,测试表明两个不可变对象通过浅复制保持相等。