My goal is to use the Builder Pattern to create the Product Details' field based on the product category.
Regardless of the product category, this is the basic ProductDetails
attributes.
int stock; // required
String ships_from; // required
String brand; // optional
Computer category could have
String model; // optional
String screen_size; // optional
String warranty_period; // optional
Food category could have
String shelf_life; // required
String expiration_date; // optional
This is the basic builder pattern I use
public class ProductDetails {
// attributes
private ProductDetails(ProductDetailsBuilder builder) {
this.attribute1 = builder.attribute1;
this.attribute2 = builder.attribute2; // and so on.
}
// getters
public static class ProductDetailsBuilder {
// attributes
public ProductDetailsBuilder(//required attributes) {
this.attribute1 = attribute1;
}
// setters
public ProductDetails build() { return new ProductDetails(this); }
}
}
The problem arise when I try to extends the ProductDetails
class to e.g ProductDetails_Computer
or ProductDetails_Food
class.
public class ProductDetails_Computer extends ProductDetails {
// attributes
private ProductDetails_Computer(ProductDetails_ComputerBuilder builder) {
this.attribute1 = builder.attribute2;
}
// getters
public static class ProductDetails_ComputerBuilder {
// attributes.
// setters
public ProductDetails_Computer build() { return new ProductDetails_Computer(this); }
}
}
My expected result: I can do public class ProductDetails_Computer extends ProductDetails
.
My actual result: Because the ProductDetails
constructor is private/protected, I can't extends. Some websites forbid the use of public constructor to avoid direct initialization, and I agree with this practices.