大话设计模式-原型模式的实践-限制订单最大数量
/*
* 订单处理系统 原型模式实现
现在有一个订单处理系统,里面有一个保存订单的业务功能,需求:
1.每当订单的预定产品数量超过1000的时候,就需要把订单拆成两份订单来保存。
2.如果拆成两份后还是超过1000,则继续拆分,直到每份产品预订数量不超过1000.
根据业务,目前的订单系统分成两种,一种是个人订单、一种是公司订单。
客户名称、产品对象(ID,Name),订购产品数量。
公司名称、产品对象(ID,Name),订购产品数量。
*/
产品类:
/**
* @ClassName: Product
* @Author: Leo
* @Description:
* @Date: 2019/4/4 19:14
*/
public class Product implements Cloneable {
private int id;
private String name;
public Product() {
}
public Product(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "ID: " + id + " Name: " + name;
}
}
订单类(包含产品对象):
/**
* 订单
*/
public class Order implements Cloneable {
private String name;
private Product product;
private int num;
public Order() {
}
public Order(String name, Product product, int num) {
this.name = name;
this.product = product;
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Name: " + name + " {" + product.toString() + "} Num: " + num;
}
}
Main:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static final int MAX_NUM = 10;
public static void main(String[] args) throws CloneNotSupportedException {
List list = new ArrayList<Order>();
Product product = new Product(1, "iPhone");
Order order = new Order("BaiDu", product, 100);
//list.add(order);
while (order.getNum() > MAX_NUM) {
Order temp = (Order) order.clone();
temp.setNum(MAX_NUM);
list.add(temp);
order.setNum(order.getNum() - MAX_NUM);
}
list.add(order);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString());
}
System.out.println(list.size());
}
}