使用一种方法将 3 种不同类型的对象添加到一个 ArrayList 的简单方法?

Easy way to add 3 different types of Objects to one ArrayList with one method?

这是我完成的作业的副本,对于一些挪威语评论,我们深表歉意。

我的问题是:
我有一个项目 ArrayList,它包含来自 类 项目、剑、药水的对象。 (药水和剑是物品的子 类)。我有 3 种不同的方法将这些对象添加到 ArrayList。

其实我的问题很简单。有没有一种方法(简单,我是新手,仍在学习)可以将所有 Items 和 Item 的 Sub类 添加到 ArrayList,而无需使用 3 种看起来很相似的不同方法。 (addItem, addSword, addPotion),都靠近代码底部。

我想要这样的东西(没有想清楚,只是写了一些东西)

public void addItem(String typeofItem){
    item = new typeofItem;
    items.add(item);
}

代码还有很多,但我觉得这才是相关的。

public class Player
{
    // Fields -------
    private String name;
    private String type;
    private int health;
    private ArrayList<Item> items = new ArrayList<>();
    private Item item;
    private Swords sword;
    private Potions potion;
    private Checker valid;
    private int maxCarry;
    private int gold;
    private int currentWeight;
    // ----------------

    /**
     * Klassens konstruktør. Players health vil alltid settes til 100.
     * 
     * @param name         Player navn
     * @param type         Player type
     * @param goldValue    Players starting gold
     * @param setMaxWeight Players max carry weight
     */
    public Player (String name, String type, int goldValue, int setMaxWeight) {
        valid = new Checker();                       // Creates a checker object to do String and integer checks

        this.name = valid.checkString(name);         // Setter player name, etter å ha sjekka at den ikke er tom
        this.type = checkType(type);                 // Setter type, etter å ha processet den
        health = 100;                                // Health skal alltid starte som 100
        maxCarry  = valid.checkInt(setMaxWeight);    // Sets max carry weight
        currentWeight = 0;                           // Start vekten til player 
        gold = valid.checkInt(goldValue);            // setter goldbeholding etter å ha sjekka at den ikke er negativ
    }

    /**
     * En metode for å selge ett Item objekt, reduserer gold og øker weight ved kjøp.
     * 
     * @param item        Item object to sell
     */
    private void buyItem(Item item)
    {
        // Temporary values given from items methods getweight and getvalue to be used in a mutation
        int tempWeight;
        int tempValue;
        tempWeight = item.getWeight();
        tempValue = item.getValue();
        // Checks if the item meets te conditions to be bought (enough gold, and can be carried)
        if (checkConditions(tempValue, tempWeight)) {
            // Adds the item to ArrayList if conditions met and updates gold and weight
            items.add(item);
            currentWeight += tempWeight;
            gold -= tempValue;
        }
    }

    /**
     * Method to calculate if given value and weight is accepted to perform a purchase (total gold > 0 && total weight < maxWeight)
     * 
     * @param value     Gold value of item
     * @param weight    Weight of item
     * @return boolean  Returns true if conditions met 
     */
    private boolean checkConditions(int value, int weight)
    {
        if (!(gold >= value))
        {
            System.out.println("You don't have enough gold!");
            return false;
        } else {
            if (!(weight + currentWeight <= maxCarry)){
                System.out.println("You'll be too heavy carry this item!");
                return false;
            } else {
                // All conditions met
                return true;
            }
        }
    }

    /**
     * Adds an item to player inventory (uses method buyItem to process the item as a purchase)
     * 
     * @param itemName    String to name item
     * @param itemDesc    String to describe item
     * @param itemValue   int to declare items value
     * @param itemWeight  int to declare items Weight
     * @param itemAction  String to give item an action
     */
    public void addItem(String itemName, String itemDesc, int itemValue, int itemWeight, String itemAction)
    {
        // A Player generated item, which needs all parameters to specify it
        item = new Item(itemName, itemDesc, itemValue, itemWeight, itemAction);
        buyItem(item);
    }

    /**
     * Randomly generates a Sword object and adds it to players inventory (uses buyItem to process)
     * @see Swords#Swords
     */
    public void addSword()
    {
        sword = new Swords();
        buyItem(sword);
    }

    /**
     * Randomly generates a Potion object and adds it to players inventory (uses buyItem to process)
     * @see Potions#Potions
     */
    public void addPotion()
    {
        potion = new Potions();
        buyItem(potion);
    }

您可以创建称为工厂的东西 class。工厂 class 的职责是为您生成一种项目的实例。

https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

本质上,您将所讨论的方法包装在 class 和 return 该对象的新实例中。

public class ItemFactory{

    public static Item addItem(String typeofItem){
        switch(typeofItem){
             case "Sword":
                return new Sword();
             case "Potion":
                return new Potion();
             ...
            default:
               //put any code here that is like the "else" of an if-else block
              return null;
        }
    }

}

然后当您需要添加特定类型的新项目时:

buyItem(ItemFactory.addItem("Sword"));