Composite
import java.util.*;
// Represents a single product
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
public void display(String indent) {
System.out.println(indent + "Product: " + name + " – ₹" + price);
}
}
// Represents a bundle of products
class ProductBundle {
private String bundleName;
private List<Product> products;
public ProductBundle(String bundleName) {
this.bundleName = bundleName;
this.products = new ArrayList<>();
}
public void addProduct(Product product) {
products.add(product);
}
public double getPrice() {
return products.stream().mapToDouble(Product::getPrice).sum();
}
public void display(String indent) {
System.out.println(indent + "Bundle: " + bundleName);
for (Product product : products) {
product.display(indent + " ");
}
}
}
// Main logic
public class Main {
public static void main(String[] args) {
// Individual Items
Product book = new Product("Book", 500);
Product headphones = new Product("Headphones", 1500);
Product charger = new Product("Charger", 800);
Product pen = new Product("Pen", 20);
Product notebook = new Product("Notebook", 60);
// Bundle: iPhone Combo
ProductBundle iphoneCombo = new ProductBundle("iPhone Combo Pack");
iphoneCombo.addProduct(headphones);
iphoneCombo.addProduct(charger);
// Bundle: School Kit
ProductBundle schoolKit = new ProductBundle("School Kit");
schoolKit.addProduct(pen);
schoolKit.addProduct(notebook);
// Add to cart logic
List<Object> cart = Arrays.asList(book, iphoneCombo, schoolKit);
// Display Cart
double total = 0;
System.out.println("Cart Details:\n");
for (Object item : cart) {
if (item instanceof Product) {
((Product) item).display(" ");
total += ((Product) item).getPrice();
} else if (item instanceof ProductBundle) {
((ProductBundle) item).display(" ");
total += ((ProductBundle) item).getPrice();
}
}
System.out.println("\nTotal Price: ₹" + total);
}
}Class Diagram

Last updated