Easy learning with example program codes

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.


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

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

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

package com.codesjava;
public class CompositePatternTest {
	public static void main(String args[]){
		Shape square = new Square();
		Shape rectangle = new Rectangle();
		FillColor fillColorObj = new FillColor();


Fill Square with color: Red
Fill Rectangle with color: Red
Fill Square with color: Blue
Please follow and like us:

Copyright © 2019 CodesJava Protection Status SiteMap Reference: Java Wiki