I am working on a class design question - design a simple grocery store with a self-checkout system I am a beginner
After briefly jotting down requirements, I started with the Product class as follows -
class Product{
String barcode;
int price;
String description;
...
}
However, some products like vegetables are priced by weight and some others like a chocolate are not. So I created 2 subclasses of Product class - ProductPricedByQuantity, ProductPricedByWeight. And added a "Rate" class attribute for ProductPricedByWeight class.
class Product{
String barcode;
String description;
...
}
class ProductPricedByQuantity extends Product{
int price;
...
}
class ProductPricedByWeight extends Product{
Rate rate;
...
}
/*example - $1 per 100 grams*/
class Rate{
int price; //$1
int measure; //100 grams
}
Now at the checkout, when the barcode of a product is scanned, if it were a ProductPricedByQuantity, then its price is simply added to the total bill amount, but if it were a ProductPricedByWeight, the price is calculated follows -
Rate rate = currentProduct.getRate();
totalPrice = (rate.getPrice()/rate.getMeasure()) * weight of the product
This approach tightly couples price (or rate) with the product classes. A simple grocery store would want to change its price often. How do I decouple these classes to ensure changing the price without having to modify product classes?
Also, what is the best design for the above scenario? (different products, priced differently)
Thanks in advance!