3

这是我的课:

public class FoodSet<T extends ConcreteFood>{
    public List<T> food = new ArrayList<T>();
    public FoodSet()
    {
        /*
        *  FoodType is an enum containing food types e.g: rice, pork, beef ...
        */
        for(FoodType foodType : FoodType.values())
        {  
            /*
            * 1(*)
            * /
            food.add( (T)new ConcreteFood(foodType,0) ) 
        }       
    }
}

在 1(*) 中是问题,如何使用 'T' 类型初始化这个列表?现在我用 ConcreteFood 初始化它,作为参数 foodType 和数量,但我的目标是用扩展 ConcreteFood 的 T 初始化这个列表。ConcreteFood 的每个子类都可以访问 foodType 和 food count。我只想用适当的 ConcreteFood 子类初始化这个列表,并用 foodType 和 count = 0 初始化每个 ConcreteFood 对象。我应该怎么做?

4

3 回答 3

1

您可以将您的FoodType enum用作工厂:

public static class ConcreteFood {
}

public static class Bacon extends ConcreteFood {
};

public static class SavoyCabbage extends ConcreteFood {
};

enum FoodType {
  Pork {
    @Override
    public ConcreteFood makeNew() {
      return new Bacon();
    }
  },
  Cabbage {
    @Override
    public ConcreteFood makeNew() {
      return new SavoyCabbage();
    }
  };

  public abstract ConcreteFood makeNew();
}

public static class FoodSet {
  public List<ConcreteFood> food = new ArrayList<ConcreteFood>();

  public FoodSet() {
    /*
     *  FoodType is an enum containing food types e.g: rice, pork, beef ...
     */
    for (FoodType foodType : FoodType.values()) {
      /*
       * 1(*)
       */
      //food.add((T) new ConcreteFood(foodType, 0)) 
      food.add(foodType.makeNew());
    }
  }
}
于 2013-03-25T13:19:56.483 回答
1

回应 OP 的回答:你真的不应该这样。我建议您也将正确的混凝土工厂传递给您FoodSet

抽象工厂:

public interface FoodFactory<T extends ConcreteFood> {
    public T create(FoodType type);
}

混凝土工厂,每个子类一个ConcreteFood

public class BagFoodFactory implements FoodFactory<BagFood> {
    private static final BagFoodFactory INSTANCE = new BagFoodFactory ();

    private BagFoodFactory () {}

    public static FoodFactory<BagFood> getInstance() { return INSTANCE; }

    public BagFood create(FoodType type) {
        return new BagFood(type, 0);
    }
}

使用您的工厂FoodSet

public class FoodSet<T extends ConcreteFood> {
    public List<T> food = new ArrayList<T>();

    public FoodSet(FoodFactory<T> factory) {
        for (FoodType foodType : FoodType.values()) {
            food.add(factory.create(foodType));
        }
    }
}

将正确的工厂传递给构造函数(无论如何你都知道这里需要哪一个)。

class Sack
{
    public FoodSet<BagFood> bagFoodSet 
            = new FoodSet<BagFood>(BagFoodFactory.getInstance());
}
于 2013-03-25T15:08:19.990 回答
1

这不是你想要的。您需要一个工厂类来为您创建 ConcreteFood 的实例。

public class FoodFactory {
    private static final FoodFactory INSTANCE = new FoodFactory();

    private FoodFactory() {}

    public static FoodFactory getInstance() { return INSTANCE; }

    public Food create(FoodType type) {
       // Put the type checks here 
    }
}

我不太关心你的命名。“混凝土食品”?听起来不开胃。为什么不是食品分类?

于 2013-03-25T12:44:40.810 回答