0

我有一个订单类:

public abstract class Order {
protected String location;
protected double price;

public Order(double price, String location){
    this.price = price;
    this.location = location;
}
public abstract double calculateBill();

public String getLocation() {
    return location;
}
public double getPrice() {
    return price;
}
public abstract String printOrder(String format);       
}

它由三个子类“NonProfitOrder”、“RegularOrder”和“OverseasOrder”扩展,每个子类仅在计算Bill() 的方式上有所不同。

然后我有和 OrderManger 类

public class OrderManager {
private ArrayList<Order> orders;

public OrderManager() {

}
public OrderManager(ArrayList<Order> orders) {
    this.orders = orders;   
}   
public void addOrder(Order o) {
    orders.add(o);
}   
public ArrayList<Order> getOrdersAbove(double val) {
    for (Order o : orders) {
        double bill = o.calculateBill();
        if (bill > val)
            orders.add(o);
    }
    return orders;
}   
public int numOrders() {
    return orders.size();
}   
public String printOrders() {
    for (Order o : orders){
        String format = "Long";
    }
    return printOrders("Long");
}
public String printOrders(String type) {
    for (Order o : orders) {

    }       
}
public double totalBill() {
    double sum = 0;
    for(Order o : orders) {
         sum = o.calculateBill();
    }
    return sum;     
}   
}

我相信我的一切工作正常,除了我遇到了 printOrders(String type) 的问题,它返回所有“type”订单的字符串,其中“type”是“Regular”、“Overseas”或“NonProfit” . 我的问题是循环遍历数组列表并仅返回给定“类型”的对象的正确方法是什么?

4

1 回答 1

1

这里的简单解决方案如下:

public String printOrders(Class orderClass) {
    StringBuilder sb = new StringBuilder();
    for (Order o : orders) {
        if(o.getClass().equals(orderClass))
        {
            sb.append(o.printOrder()).append("\n");
        }
    }
    return sb.toString();       
}

然后当你调用该方法时:

String orderString = orderManager.printOrders(NonProfitOrder.class);
System.out.println(orderString);
于 2013-09-19T16:41:35.613 回答