我有几个类。通用订单从产品类中的东西收集,这些东西只是一些对象,如水果和计算机零件。计算机顺序扩展了 GenericOrder,它使用产品类中的一些对象创建自己的集合,因此计算机订单有自己的集合,称为 computerOrder。现在有第三个集合叫做orderProcessor,我认为队列的使用很好,它的第一个先出方式。
将 genericOrder 和 computerOrder 添加到 orderProcessor 的最佳方法是什么? 我在将 computerOrder 添加到 orderProcessor 时遇到错误。有没有更好的方法或我走在正确的轨道上?
import java.util.*;
public class GenericOrder <T extends Product> {
List<Product> genericOrder;
public void compPrice(float comPrice){
genericOrder.add(new ComputerPart(comPrice));
Product a = genericOrder.get(0);
}
}
import java.util.*;
public class ComputerOrder extends GenericOrder<Product> {
ArrayList<Product> computerOrder;
public void addDrive (String dType, int dSpeed, float price) {
computerOrder.add(new Drive(dType ,dSpeed ,price));
}
import java.util.ArrayList;
public class OrderProcessor extends GenericOrder<Product>{
ArrayList<Product> orderProcessor;
protected int queSize=0;
protected int front=0, rear;
public void accept()// this method accepts a GenericOrder or any of its subclass objects and stores it in any internal collection of OrderProcessor.
{
orderProcessor.addAll(genericOrder);
orderProcessor.addAll(genericOrder.computerOrder);
orderProcessor.addAll(partyTrayOrder);
}
也许你看起来像这样:
public class Order<T extends Product> {
List<T> products;
public void add(T productItem) {
}
}
public class ComputerOrder extends Order<ComputerPart> {
//I think, you don't need collection of ComputerParts here, cause you have it in the parent class
//Maybe you either don't need method like addDrive — you can use add(new Drive()) instead
}
//It's better to prefer composition over inheritance
public class OrderProcessor {
List<Product> products;
public void accept(List<? extends Product> products) {
this.products.addAll(products);
}
}
您可以通过以下方式使用 OrderProcessor:
OrderProcessor orderProcessor = new OrderProcessor();
orderProcessor.accept(new ArrayList<Product>());
orderProcessor.accept(new LinkedList<ComputerPart>());
orderProcessor.accept(new CopyOnWriteArrayList<SomethingExtendingProduct>());