Composite Design Pattern
Composite design pattern is used when we need to represent a part-whole hierarchy. For example, you go to a restaurant, there the attendant can give you a menu booklet that contains everything. On the contrary, at some restaurants you can have separate menu for food, separate for desserts, and a separate one for drinks. The all 3 will collectively constitute the entire menu of the restaurant.
In the below example, we will implement the similar solution.
FoodType interface
package com.sks.composite;
public interface FoodType {
void getInfo();
}
FoodItem abstract class
package com.sks.composite;
public abstract class FoodItem implements FoodType {
protected String name;
protected int price;
public FoodItem(String name, int price) {
super();
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "FoodItem [name=" + name + ", price=" + price + "]";
}
}
GravyItem.java
package com.sks.composite;
public class GravyItem extends FoodItem {
public GravyItem(String name, int price) {
super(name, price);
}
@Override
public void getInfo() {
System.out.println("Item Name : " + this.name);
System.out.println("Price : " + this.price);
}
}
Bread.java
package com.sks.composite;
public class Bread extends FoodItem {
@Override
public void getInfo() {
System.out.println("Item Name : " + this.name);
System.out.println("Price : " + this.price);
}
public Bread(String name, int price) {
super(name, price);
}
}
Sweet.java
package com.sks.composite;
public class Sweet extends FoodItem {
@Override
public void getInfo() {
System.out.println("Item Name : " + this.name);
System.out.println("Price : " + this.price);
}
public Sweet(String name, int price) {
super(name, price);
// TODO Auto-generated constructor stub
}
}
Menu.java
package com.sks.composite;
import java.util.ArrayList;
import java.util.List;
public class Menu implements FoodType {
private List<FoodType> menu = new ArrayList<>();
@Override
public void getInfo() {
for (FoodType f : menu) {
f.getInfo();
}
}
public void add(FoodType foodType) {
menu.add(foodType);
}
}
CompositePatternTest
package com.sks.composite;
public class CompositePatternTest {
public static void main(String[] args) {
FoodItem dal = new GravyItem("Dal Tadka", 250);
FoodItem paneer = new GravyItem("Kadhai Paneer", 350);
FoodItem roti = new Bread("Tandoori Roti", 50);
Menu lunchMenu = new Menu();
lunchMenu.add(dal);
lunchMenu.add(roti);
lunchMenu.add(paneer);
FoodItem iceCream = new Sweet("Mango ice cream", 200);
FoodItem gulabJamun = new Sweet("Gulab Jamun", 100);
Menu dessertMenu = new Menu();
dessertMenu.add(iceCream);
dessertMenu.add(gulabJamun);
Menu mainMenu = new Menu();
mainMenu.add(lunchMenu);
mainMenu.add(dessertMenu);
mainMenu.getInfo();
}
}
Output :