I have a class called SalesOrder(SO) that allows users to buy multiple items in the same order. SO has an order number.
class SalesOrder {
public String orderNumber;
}
Each SO has many elements, so I created a new class OrderItemthat has the name and price of the element.
class OrderItem {
public String name;
public double price;
}
Each SO has an order header, including username and address. It also has a field called the total price, which contains the sum of all the prices of the goods
class OrderHeader {
public String username;
public String address;
public double totalPrice;
}
After that, I added two fields to SO:
class SalesOrder {
...
public List<OrderItem> items;
public OrderHeader header;
}
Since OrderItem and OrderHeader are always used with SalesOrder, and the header should return the prices of all products, I turned them into SalesOrder inner classes.
class SalesOrder {
...
public SalesOrder() {
this.items = new ArrayList<>();
this.header = new OrderHeader();
}
public class OrderItem {
...
}
public class OrderHeader {
...
public double getTotalPrice() {
double total = 0.0;
total += items[i].price;
return total;
}
}
}
, - ? , ?
======= =======
, .
construe private, SalesOrder.
SalesOrder factory
class SalesOrder {
...
public SalesOrder parseOrder(Xml xml) {
this.header = new OrderHeader(valueFromXml, valueFromXml);
}
public class OrderHeader {
....
private OrderHeader(username, address) { ... }
}
public Class OrderItem {
...
private OrderItem(name, price) { ... }
}
}
Xml xml = orderXmlData;
SalesOrder order = SalesOrder.parseOrder(orderXmlData);
OrderItem item = order.item;
OrderHeader header = order.header;