我正在写我的新Java项目,要求是代表可以属于某个类别的产品。
我在项目中使用数据库,并通过外键连接产品和类别。
相反,在代码中,我必须使用SOLID设计,但我不理解如何连接产品和类别。
在第一个版本中,代码是

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; }

}


...但是我认为该产品可以实现类别,以便将所有信息包含在一个对象中,而不是在两个类之间跳转...

哪种写法是最好的?

最佳答案

您不应逐字模仿Java类中的基础数据库表结构。正确的操作方式以及我迄今为止使用的每种ORM方法都使用的正确方法如下:


Product类存储对Category实例的引用。
从数据访问层中的数据库中获取记录时,您将显式编写代码以首先创建Category对象,然后在创建Product对象时将其传递给Product类构造函数。


这样,Java类层次结构反映了Product及其相关的Category之间的真实业务关系。这还具有从应用程序中抽象存储详细信息的优势-考虑如果将数据存储在NoSQL数据库中,当前采用的方法会发生什么。但是,通过采用此答案中提出的方法,您只需更改数据访问层即可创建正确的对象-您的类设计保持完整(SOLID中的“开-闭”原理的O)。

10-07 19:18
查看更多