Composite Design Pattern in java

  • It is a structural design pattern
  • Composite Design pattern will have a tree structure
  • Leaf node in a composite design pattern tree is the one which is at the end of the tree
  • If you can perform some operation on leaf node, the same operation need to be performed on the leaf node.
public class ComputerPart {
	
}

interface Component {
	void showPrince();
}

class Leaf implements Component {
	int price;
	String name;
	
	public Leaf(int price, String name) {
		super();
		this.price = price;
		this.name = name;
	}

	@Override
	public void showPrince() {
		System.out.println(name + " : " + price);
	}
}

class Composite implements Component {
	String name;
	List<Component> componentList = new ArrayList<>();

	public Composite(String name) {
		super();
		this.name = name;
	}

	public void addComponent(Component component) {
		componentList.add(component);
	}

	public void showPrince() {
		System.out.println(name);
		for (Component c : componentList) {
			c.showPrince();
		}
	}
}
public class CompositeTest {
	public static void main(String[] args) {
		Component hd = new Leaf(4000,"HDD");
		Component mouse = new Leaf(500,"Mouse");
		Component monitor = new Leaf(2000,"Monitor");
		Component ram = new Leaf(8000,"Ram");
		Component cpu = new Leaf(25000,"CPU");
		
		Composite ph = new Composite("Peri");
		Composite cabinet = new Composite("Cabinet");
		Composite mb = new Composite("MB");
		Composite computer = new Composite("Computer");
		
		mb.addComponent(ram);
		mb.addComponent(cpu);
		
		ph.addComponent(mouse);
		ph.addComponent(monitor);
		cabinet.addComponent(hd);
		cabinet.addComponent(mb);
		
		computer.addComponent(ph);
		computer.addComponent(cabinet);
		
		computer.showPrince();
	}
}

Leave a Comment