我正在编写我的新java项目,一个要求是表示可以属于某个类别的产品。我在我的项目中使用一个数据库,我用外键连接产品和类别。相反,在代码中,我必须使用可靠的设计,我不知道如何将产品和类别连接起来。在第一个版本中,代码是
public class Product {
private int ID;
private String name;
private String descr;
private int stock;
private float price;
private int category;
public Product(int anID, String aName, String aDescr, int aStock, float aPrice, int aCategory) {
this.ID = anID;
this.name = aName;
this.descr = aDescr;
this.stock = aStock;
this.price = aPrice;
this.category = aCategory;
}
public int getID() { return this.ID; }
public String getName() { return this.name; }
public String getDescr() { return this.descr; }
public int getStock() { return this.stock; }
public float getPrice() { return this.price; }
public int getCategory() { return this.category; }
public void decreaseStock(int x) { this.stock -= x; }
}
和
public class Category {
private int ID;
private String name;
private String descr;
public Category (int anID, String aName, String aDescr) {
this.ID = anID;
this.name = aName;
this.descr = aDescr;
}
public int getID() { return this.ID; }
public String getName() { return this.name; }
public String getDescr() { return this.descr; }
}
..。但是我认为产品可以实现类别,为了使所有信息都在一个对象中而不是在两个类之间跳转.
写它的最好方法是哪一种?
发布于 2016-07-30 17:03:59
您不应该逐字模仿Java类中的底层数据库表结构。到目前为止,我所使用的每一种ORM方法都有如下正确的方法:
Product
类存储对Category
实例的引用。Category
对象,然后在创建Product
对象时将其传递给Product
类构造函数。这样,Java类层次结构反映了Product
与其相关的Category
之间的真正业务关系。这还具有将存储细节从应用程序中抽象出来的优点--考虑一下如果将数据存储在NoSQL数据库中,当前采用的方法会发生什么情况。但是,通过采用这个答案中给出的方法,您只需要更改数据访问层以创建正确的对象--您的类设计保持不变( O of Open-Closed principle in SOLID)。
https://stackoverflow.com/questions/38676138
复制相似问题