【问题标题】:Assigning a Variable the Identity of Another将另一个变量的身份分配给一个变量
【发布时间】: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.amountItem.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.amountItem.amount
  • 那是因为你不应该同时改变两者,也不应该同时改变两者。

标签: java pass-by-reference identity


【解决方案1】:

不要给 ItemNode 类一个数量字段,因为这样做会创建“并行字段”,并且必须努力确保它们保持同步,而实际上它们很容易不同步。相反,更简单地为您的 ItemNode 类提供一个公共 getAmount() 方法,该方法简单地调用并返回其项目的 getAmount() 方法。如果您需要 setter 方法,则相同。请记住使您的代码尽可能地防白痴。还要研究一下装饰器设计模式,因为这个问题似乎已经部分解决了。

public interface Amountable {

    int getAmount();

    void setAmount(int amount);

}

public class Item implements Amountable {
    private int amount;

    public Item(int amount) {
        this.amount = amount;
    }

    @Override
    public int getAmount() {
        return amount;
    }

    @Override
    public void setAmount(int amount) {
        this.amount = amount;
    }

}

public class ItemNode<T extends Amountable> implements Amountable {
    private T item;

    public ItemNode(T item) {
        this.item = item;
    }

    @Override
    public int getAmount() {
        return item.getAmount();
    }

    @Override
    public void setAmount(int amount) {
        item.setAmount(amount);
    }    

    public T getItem() {
        return item;
    }
}

【讨论】:

  • 总经理鳗鱼先生。不相关的问题:我看到您的活动资料显示 61K “投票”。只是想知道:我的理解是,这个数字显示了所有投票......对未删除的内容。现在我很好奇你是怎么得到这个数字的?前一周我做了很多密切评论(从队列中),但似乎这些项目中的许多项目后来......关闭并删除。因此,该计数器的增长速度非常缓慢。换句话说:你有一些特定的“模式”吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 2018-03-17
  • 1970-01-01
  • 2018-06-13
  • 2015-09-12
相关资源
最近更新 更多