2015-08-14 54 views
0

我正在設計一個管理項目的軟件。Java如何處理一個對象的類型

該軟件有多種產品類型 - 每種都有自己的SKU和物理屬性,用戶可以動態地添加這些產品類型。

該軟件還具有項目(也動態添加) - 每個項目都屬於產品類型(繼承其特定屬性)。當用戶添加項目時,他們需要能夠選擇產品類型,用戶還可以添加其他屬性,例如項目是否損壞,打開或新建等屬性。

在我目前的設計中,我有一類ProductType,它具有產品類型所有屬性的字段。我也有一類item,它具有其他屬性的字段。

我很困惑如何讓類Item的對象繼承類的特定對象的屬性。任何意見,將不勝感激。該設計在第一次修訂中,所以可以很容易地進行修改。

我的第一個想法是全局存儲一個ProductType數組,然後創建一個項目時使用一個函數來複制這些字段。這會工作還是有更好的方法?

+0

您可以使用簡單的類層次結構嗎? public class Item ** extends ** ProductType {} –

+0

是的,我在想這個,但我會手動添加字段值? – Reid

+0

那麼你有一個網站運行,可以填補這些?也許你應該看看spring mvc,看看如何構建簡單的jsps和表單來填充你的對象 –

回答

0

public class Item extends ProductType{}

+0

是的,但是如何將特定產品類型的值存入項目中,我是否會手動複製? – Reid

+0

@Reid會不會做的伎倆? – cadams

+0

字段,但據我所知,字段的內容不會在創建新對象時進行復制。 – Reid

2

我覺得你的問題的最佳解決方案是使用組成:該類型項目的屬性。

public class Item() { 
    private final ProductType type; 
    // other properties 

    public Item(ProductType type) { 
     this.type = type; 
    } 
} 
+0

這使得很多意義。謝謝! – Reid

+0

@Reid歡迎您:) – SimoV8

0

您不應該複製這些字段,而應該參考ProductType。您也不應直接訪問ProductType的字段,但只能通過getter方法訪問,如果您想「繼承」這些字段,則應該將委派方法添加到您的Item類中。

public class ProductType { 
    private String typeName; 
    public ProductType(String typeName) { 
     this.typeName = typeName; 
    } 
    public String getTypeName() { 
     return this.typeName; 
    } 
} 

public class Item { 
    private ProductType productType; 
    private String  itemName; 
    public Item(ProductType productType, String itemName) { 
     this.productType = productType; 
     this.itemName = itemName; 
    } 
    // Access to ProductType object (optional) 
    public ProductType getProductType() { 
     return this.productType; 
    } 
    // Delegated access to ProductType field 
    public String getTypeName() { 
     return this.productType.getTypeName(); 
    } 
    // Access to Item field 
    public String getItemName() { 
     return this.itemName; 
    } 
} 
相關問題