2015-08-14 53 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; 
    } 
} 
相关问题