我们有:
public final class Product {
Integer productId;
String description;
...
public Product(final Integer productId, final String descripcion, ...) {
this.product_id = productId;
this.description = description;
...
}
public Integer getProductId() { ... }
public String getDescription() {...}
...
}
然后:
public final ProductDetails {
Integer productId;
String serialNumber;
...
public ProductDatails(final Integer productId, final serialNumber, ...){ ... }
public Intger getProductId() { ... }
public String getSerialNumber { ... }
...
}
因此,为了构建一个持久化两个类所包含的数据的DAO,问题是如果这样做是一个好的做法,如下所示:
public Interface IProductDAO {
public void saveProduct(final Product product);
public void saveProductDetails(final ProductDetails productDetails);
}
或:
public Interface IProductDAO {
public void saveProduct(final Product product, final ProductDetails productDetails);
我一直在考虑将这两个类重构为一个如下:
public final class Product {
Integer productId;
String description;
ProductDetails productDetails;
...
public Product(final productId productId, final String description, final ProductDetails productDetails,...) {
if(productId!=productDetails.getProductId())
throw new IllegalArgumentException("ProductID is not the same");
...
}
}
所以:
public Interface IProductDAO {
public void saveProduct(final Product product);
}
我想知道根据最佳软件开发实践,哪一种是最“自然”的方法。如果还有其他方法,他们也会受到欢迎。
答案 0 :(得分:0)
最佳方法是你有两个java类。一个是产品,第二个是ProductDetails,您可以在其中获得产品的更多详细信息。当用户单击产品时,您可以获取此类以显示此特定项目的更多详细信息。
因此,需要在搜索页面中显示的最基本细节可以在产品类中找到。
class Product {
Integer productId;
String description;
@OneToOne
@Basic(Fetch = FetchType.LAZY)
ProductDetails details;
public Product(final Integer productId, final String descripcion, ...) {
this.product_id = productId;
this.description = description;
...
}
public Integer getProductId() { ... }
public String getDescription() {...}
...
}
class ProductDetails{
Integer productId;//any Id
String description;
//Storing a HD picture and other getters and setters
}
//details of the class
}
答案 1 :(得分:0)
根据Bertrand Meyer - Object Oriented Software Construction (2Ed)
,Product类应该包含对ProductDetails的引用,因为这些类之间存在很强的关系。
另一方面,从Product类扩展以生成新的ProductDetails类是一种很好的做法。在这两种情况下,DAO应如下:
public void saveProduct(final Product product);