Tutorial

Composite Design Pattern in Java

Published on August 3, 2022
author

Pankaj

Composite Design Pattern in Java

Composite pattern is one of the Structural design pattern. Composite design pattern is used when we have to represent a part-whole hierarchy.

Composite Design Pattern

composite pattern, composite design pattern When we need to create a structure in a way that the objects in the structure has to be treated the same way, we can apply composite design pattern. Lets understand it with a real life example - A diagram is a structure that consists of Objects such as Circle, Lines, Triangle etc. When we fill the drawing with color (say Red), the same color also gets applied to the Objects in the drawing. Here drawing is made up of different parts and they all have same operations. Composite Pattern consists of following objects.

  1. Base Component - Base component is the interface for all objects in the composition, client program uses base component to work with the objects in the composition. It can be an interface or an abstract class with some methods common to all the objects.
  2. Leaf - Defines the behaviour for the elements in the composition. It is the building block for the composition and implements base component. It doesn’t have references to other Components.
  3. Composite - It consists of leaf elements and implements the operations in base component.

Here I am applying composite design pattern for the drawing scenario.

Composite Pattern Base Component

Composite pattern base component defines the common methods for leaf and composites. We can create a class Shape with a method draw(String fillColor) to draw the shape with given color. Shape.java

package com.journaldev.design.composite;

public interface Shape {
	
	public void draw(String fillColor);
}

Composite Design Pattern Leaf Objects

Composite design pattern leaf implements base component and these are the building block for the composite. We can create multiple leaf objects such as Triangle, Circle etc. Triangle.java

package com.journaldev.design.composite;

public class Triangle implements Shape {

	@Override
	public void draw(String fillColor) {
		System.out.println("Drawing Triangle with color "+fillColor);
	}

}

Circle.java

package com.journaldev.design.composite;

public class Circle implements Shape {

	@Override
	public void draw(String fillColor) {
		System.out.println("Drawing Circle with color "+fillColor);
	}

}

Composite object

A composite object contains group of leaf objects and we should provide some helper methods to add or delete leafs from the group. We can also provide a method to remove all the elements from the group. Drawing.java

package com.journaldev.design.composite;

import java.util.ArrayList;
import java.util.List;

public class Drawing implements Shape{

	//collection of Shapes
	private List<Shape> shapes = new ArrayList<Shape>();
	
	@Override
	public void draw(String fillColor) {
		for(Shape sh : shapes)
		{
			sh.draw(fillColor);
		}
	}
	
	//adding shape to drawing
	public void add(Shape s){
		this.shapes.add(s);
	}
	
	//removing shape from drawing
	public void remove(Shape s){
		shapes.remove(s);
	}
	
	//removing all the shapes
	public void clear(){
		System.out.println("Clearing all the shapes from drawing");
		this.shapes.clear();
	}
}

Notice that composite also implements component and behaves similar to leaf except that it can contain group of leaf elements. Composite Pattern, Composite Design Pattern Java Our composite pattern implementation is ready and we can test it with a client program.

Composite Design Pattern Client Program

TestCompositePattern.java

package com.journaldev.design.test;

import com.journaldev.design.composite.Circle;
import com.journaldev.design.composite.Drawing;
import com.journaldev.design.composite.Shape;
import com.journaldev.design.composite.Triangle;

public class TestCompositePattern {

	public static void main(String[] args) {
		Shape tri = new Triangle();
		Shape tri1 = new Triangle();
		Shape cir = new Circle();
		
		Drawing drawing = new Drawing();
		drawing.add(tri1);
		drawing.add(tri1);
		drawing.add(cir);
		
		drawing.draw("Red");
		
		drawing.clear();
		
		drawing.add(tri);
		drawing.add(cir);
		drawing.draw("Green");
	}

}

Output of the above composite pattern client program is:

Drawing Triangle with color Red
Drawing Triangle with color Red
Drawing Circle with color Red
Clearing all the shapes from drawing
Drawing Triangle with color Green
Drawing Circle with color Green

Composite Pattern Important Points

  • Composite pattern should be applied only when the group of objects should behave as the single object.
  • Composite design pattern can be used to create a tree like structure.

java.awt.Container#add(Component) is a great example of Composite pattern in java and used a lot in Swing. Earlier structural design pattern articles:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 12, 2020

Great example. The Shape interface name should be Drawable to follow naming conventions and to describe what the interface adds to a class. Basically a drawing is a composition of drawable elements such as shapes and lines. The class name Shape would be better suited for an Abstract Class.

- Stephane Tremblay

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 29, 2019

    Hi Pankaj your blog is really helpful to me. I just want to say thanks to you.

    - taotao

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 19, 2017

      This is not composite pattern. check this for right explanation https://www.dofactory.com/net/composite-design-pattern. in composite pattern there have to be nodes and leaves to form a tree. Just aggregating objects into another object is not a composite pattern.

      - ravi

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 5, 2017

        Nice article pankaj, you are the champ.

        - Manoj Singh

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          December 9, 2014

          Thanks a lot ! Your tutorials were so useful for me !!! and i’m sure, i’m not the only one ! Design Patterns especially, That got me a good mark in my exams :)))) Thanks; another time !!! Good Continuation !

          - Nabil Amrouche

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 28, 2014

            Really nice post. help me a lot to get the concept.

            - perminder singh

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              March 13, 2014

              It really help me a lot… Can you give an example of composite pattern that has a GUI Thank you!!!

              - Zhacantal

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 14, 2013

                I like the example you have provided.

                - Amit

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  July 6, 2013

                  Hi Pankaj, Thanks for sharing best core java tutorial for freshers and experience. Its really helpful for java developer. kindly request to you please share Spring MVC+Hibernate application as per industry stranded and useful for better performance. Thanks and Regards Yogesh Kharode

                  - Yogesh Kharode

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Become a contributor for community

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    DigitalOcean Documentation

                    Full documentation for every DigitalOcean product.

                    Resources for startups and SMBs

                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                    Get our newsletter

                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                    New accounts only. By submitting your email you agree to our Privacy Policy

                    The developer cloud

                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Get started for free

                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                    *This promotional offer applies to new accounts only.