Java composite design pattern

In programming languages, composite normally used with tree structures.

Java composite design pattern comes under structural design patterns and it provides the facility to compose objects into tree structures to represent part-whole hierarchies i.e. individual and composite objects will be treated uniformly.

A composite design pattern consists of following objects:

  1. Base Component: It will represents an interface for all objects in the composition.
  2. Leaf: It represents leaf objects in composition. A leaf doesn’t have references to other Components. It will implement the Base Component.
  3. Composite: It will contains the leaf components and provides the implementation of base component operations.

Example

Shape.java

package com.w3schools;
 
public interface Shape {
	public void fillColor(String color);
}

Square.java

package com.w3schools;
 
public class Square implements Shape {
	@Override
	public void fillColor(String color) {
		System.out.println("Fill Square with color: "+color);
	}
}

FillColor.java

package com.w3schools;
 
import java.util.ArrayList;
import java.util.List;
 
public class FillColor implements Shape {
	//List of Shapes
	private List<Shape> shapes = new ArrayList<Shape>();
 
	@Override
	public void fillColor(String color) {
		for(Shape shape : shapes) {
			shape.fillColor(color);
		}
	}
 
	//Add shape to FillColor
	public void add(Shape shape){
		this.shapes.add(shape);
	}
 
	//Remove shape from FillColor
	public void remove(Shape shape){
		shapes.remove(shape);
	}
}

CompositePatternTest.java

package com.w3schools;
 
public class CompositePatternTest {
	public static void main(String args[]){
		Shape square = new Square();
		Shape rectangle = new Rectangle();
 
		FillColor fillColorObj = new FillColor();
		fillColorObj.add(square);
		fillColorObj.add(rectangle);		
		fillColorObj.fillColor("Red");
 
		fillColorObj.remove(rectangle);
 
		fillColorObj.fillColor("Blue");
	}
}

Output

Fill Square with color: Red
Fill Rectangle with color: Red
Fill Square with color: Blue