【发布时间】:2018-11-26 01:45:49
【问题描述】:
我有一个 Item 类。每个 Item 对象都保存在 ItemNode 类的一个实例中。 ItemNode 是我的 CustomList 类中的一个内部类。
我的 Item 类有一个名为 amount 的属性。这是指用户拥有多少此类项目
我的 ItemNode 类还有一个名为 amount 的属性。我希望 ItemNode 的 amount 属性始终等于它所拥有的 Item 对象的 amount 属性。
换句话说,(ItemNode.amount == ItemNode.item.amount) 应该始终为真,即使我稍后更改了 itemNode.amount 的值。
如何使 Java 对 ItemNode.amount 和 Item.amount 具有相同的标识?
我的 ItemNode 类:
/**
* Creates nodes to hold Item objects.
*/
private class ItemNode {
// the object being held by the node
private Item item;
// The type of the object
private String typeName;
// How many are owned by the player
private int amount;
// What the item-subclass's name is
private String itemName;
// the node after this
private ItemNode next;
ItemNode(Item item) {
this.data = item;
this.typeName = typeName;
this.itemName = item.getItemName();
this.amount = item.getAmount();
this.next = null;
}
}
【问题讨论】:
-
1) 不要给 ItemNode 一个金额字段。相反,只需让 ItemNode 中的
getAmount()方法返回它所持有的项目的值。不多也不少。 Decorator 设计模式可能正是您想要的。 -
但这不会让我同时更改
ItemNode.amount和Item.amount。 -
那是因为你不应该同时改变两者,也不应该同时改变两者。
标签: java pass-by-reference identity