gpt4 book ai didi

Java : Duplication of methods

转载 作者:行者123 更新时间:2023-12-03 19:07:57 26 4
gpt4 key购买 nike

这感觉像是一个基本问题,但这对我来说是全新的:

我有一个 Person 和 Room 类,它们都有一个 Item 对象列表。

public class Person{
private ArrayList<Item> items;

public Person() {
items = new ArrayList<>();
}

public void addItem(){
...
}

public void removeItem(){
...
}

}

public class Room {

private ArrayList<Item> items;

public Room () {
items = new ArrayList<>();
}

public void addItem(){
...
}

public void removeItem(){
...
}

}

项目方法,例如addItem() 在 Room 类和 Person 类中都是重复的,这不是很好。我考虑制作一个单独的 Inventory 类,其中包含项目列表和项目方法,然后每个房间和每个人都会有一个库存。

但是如果我使用私有(private) Inventory 字段,我将无法从 Person 或 Room 调用 Item 方法。

在这里停止重复的最佳方法是什么?提前致谢!

最佳答案

你是对的。制作一个单独的库存类将是一个很好的 OOP 设计。

我很高兴你没有说为 RoomPerson 创建父类,因为虽然那样可以避免重复,但 Rooms 和 Person 是不相关的所以它们也不应该在面向对象的意义上真正相关。

您可以使用委托(delegate)将添加/删除项目委托(delegate)给您的 Inventory 字段。

public class Room {

private Inventory inventory = new Inventory();

public void addItem(Item item) {
inventory.addItem(item);
}

public void removeItem(Item item) {
inventory.removeItem(item);
}
}

编辑

有些人提议公开库存,然后在该 person.getInventory().addItem(item) 上使用公共(public)添加/删除方法。我认为这会违反 Law of Demeter

关于Java : Duplication of methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26413871/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com