2016-07-30 47 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)。