如何以正确的方式存储域对象

时间:2013-10-17 11:05:36

标签: android inheritance

我有两个类,第一个叫做Product,基本上包含从数据库加载的所有可用产品及其属性。另一个类称为OrderProduct,扩展Product并且还有两个属性:数量和日期。 OrderProduct用作保存当前订单信息的临时对象。在订单结束时,订单对象将保存到数据库中。我的问题:我应该遵循我当前的结构,还是按照OrderProduct不会扩展Product类的方式进行设计,并且只保留id来访问特定产品并具有以下两个附加属性:数量和日期?或者有更好的方法如何做到这一点?

产品:

package domainLayer;

public class Product {

    private int id;
    private String name;
    private String description;
    private String type;
    private int price;
    private String status;

    public Product(int id, String name, int price, String type, String description, String status) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.price = price;
        this.status = status;
    }

    public Product(Product product){
        this.id = product.getId();
        this.name = product.getName();
        this.description = product.getDescription();
        this.price = product.getPrice();
        this.status = product.getStatus();
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getPrice() {
        return price;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }
}

OrderProduct:

package domainLayer;

import java.util.Date;

public class OrderProduct extends Product {

    private int quantity;
    private Date date;

    public OrderProduct(int id, String name, int price, String type, String description, String status, int quantity, Date date) {
        super(id, name, price, type, description, status);
        this.quantity = quantity;
        this.date = date;
    }

    public OrderProduct(Product product, int quantity, Date date){
        super(product);
        this.quantity = quantity;
        this.date = date;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int getQuantity() {
        return quantity;
    }

    public void addQuantity(int quantity){
        this.quantity += quantity;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Date getDate() {
        return date;
    }
}

1 个答案:

答案 0 :(得分:0)

我不会这样做。 OrderProduct不是真正的子类,因此它不应该是Product的子类。

而是使用产品,数量,日期等的getter创建OrderProduct。