public class InventorySetDAO{
public LinkedList<CustomInventory> inventories = new LinkedList<>();
}
我正在开发在arraylist中添加/删除数据的插件。并且其他类的arrayList上的引用过多。
Class InventoryItemModifier:
public class InventoryItemModifier {
InventorySetDAO inventorySetDAO;
public InventoryItemModifier(InventorySetDAO inventorySetDAO){
this.inventorySetDAO = inventorySetDAO;
}
public void addItem(ItemStack itemStack, ClickAction click, RequiredItems requiredItems) {
Bukkit.getPluginManager().callEvent(new ItemAddedEvent());
inventorySetDAO.getLastInventory().addItem(itemStack, click, requiredItems);
}
public void removeItem(ItemStack itemStack){
Bukkit.getPluginManager().callEvent(new ItemRemovedEvent());
inventorySetDAO.getLastInventory().removeItem(itemStack);
}
}
Class InventoryPlayerAccessor:
public class InventoryPlayerAccessor {
InventorySetDAO inventorySetDAO;
public boolean openPage(Player player) {
if (!inventories.isEmpty()) {
inventories.get(0).openInventory(player);
return true;
}
return false;
}
public boolean openPage(Player player, int index) {
if (!inventories.isEmpty()) {
if (index >= 0 && index < inventories.size()) {
inventories.get(index).openInventory(player);
return true;
}
}
return false;
}
}
我认为存在操作不正确的arrayList的风险,因此我认为arrayList必须在一个类中并提供方法(添加/插入/删除...),但是如果那样的话,该类中的职责太多。
我试图将它们分成多个类,但似乎无法解决此问题。有没有办法减少对arrayList的依赖,还是封装arrayList的有效方法?
为了减少每个类对基础ArrayList(或仅List)的依赖,您可以考虑使用复合模式而不是DAO模式。这将隐藏InventorySet类的所有/大部分逻辑。
class InventorySet {
private final List<CustomInventory> inventories = new ArrayList<>();
public void addItem() { }
public void removeItem() { }
}
然后,您可以只保留InventoryPlayerAccessor(也许重命名),但是将其组成一个InventorySet以便于访问。
class InventorySetView {
void open();
}