Java 将产品连接到类别
我正在编写我的新java项目,其中一个需求是表示可以属于某个类别的产品。 我在我的项目中使用一个数据库,通过外键连接产品和类别。 相反,在代码中,我必须使用实体设计,我不知道如何连接产品和类别。 在第一个版本中,代码是Java 将产品连接到类别,java,software-design,solid-principles,Java,Software Design,Solid Principles,我正在编写我的新java项目,其中一个需求是表示可以属于某个类别的产品。 我在我的项目中使用一个数据库,通过外键连接产品和类别。 相反,在代码中,我必须使用实体设计,我不知道如何连接产品和类别。 在第一个版本中,代码是 public class Product { private int ID; private String name; private String descr; private int stock; private float price
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; }
}
及
。。。但我认为产品可以实现类别,以便在一个对象中包含所有信息,而不是在两个类之间跳跃
编写它的最佳方法是什么?您不应该在Java类中逐字模仿底层数据库表结构。正确的方法以及我迄今为止所研究的每种ORM方法的使用方法如下:
产品
类存储对类别
实例的引用类别
对象,然后在创建产品
对象时将其传递给产品
类构造函数产品
与其相关的类别
之间的真正业务关系。这还具有从应用程序中抽象存储细节的优点-考虑如果数据被存储在NoSQL数据库中,您当前采用的方法会发生什么。然而,通过采用本答案中提出的方法,您只需更改数据访问层即可创建正确的对象-您的类设计保持不变(在SOLID中开闭的O原则)
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; }
}