2016-07-30 52 views
0

我正在编写我的新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; } 

} 

...但我认为产品可以工具类别,以便在一个所有信息对象,而不是在两个类之间跳转...

哪一个是写它的最好方法?

回答

2

您不应该逐字模仿Java类中的底层数据库表结构。正确的方法做,并且我的工作,直到每一个ORM的方法现在使用如下:

  1. Product类存储到Category实例的引用。
  2. 从数据访问层中的数据库中提取记录时,您需要明确编写代码以创建Category对象,然后在创建Product对象时将其传递给Product类构造函数。

这样,Java类层次结构反映了Product与其相关的Category之间的真实业务关系。这也具有从应用程序中抽象存储细节的优势 - 考虑如果将数据存储在NoSQL数据库中,您正在采用的方法会发生什么。但是,通过采用此答案中介绍的方法,您只需更改数据访问层以创建正确的对象 - 您的类设计保持不变(O开放式关闭原理SOLID)。