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

时间:2016-10-07 13:33:08

标签: java arraylist methods subclass

这是我所做的任务的副本,所以为挪威的一些评论道歉。

我的问题是:
我有一个项目ArrayList,它包含Item,Swords,Potions类中的对象。 (Potions& Swords是Items的子类)。我有3种不同的方法将这些对象添加到ArrayList。

我的问题实际上很简单。有没有(简单的,我是新的和学习的)方式让我将所有项目的子项和子类添加到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);
    }

1 个答案:

答案 0 :(得分:1)

您可以创建一个名为Factory类的东西。工厂类的职责是为您生成一种项目的实例。

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

基本上,您将在类中包含的方法包装起来并返回该对象的新实例。

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"));