Composite Design Pattern Tutorial

Composite Design Pattern TutorialWelcome to my Composite Design Pattern Tutorial! The Composite design pattern is used to structure data into its individual parts as well as represent the inner workings of every part of a larger object.

The composite pattern also allows you to treat both groups of parts in the same way as you treat the parts polymorphically. This allows your objects to maximize complexity while also remaining dynamic.

All of the code follows the video to help you learn. It is heavily commented.

If you think others would benefit from this video, it helps to tell Google with a click

Share if you no others may like this

Code from the Video


// This acts as an interface for every Song (Leaf)
// and SongGroup (Composite) we create

public abstract class SongComponent {
	// We throw UnsupportedOperationException so that if
	// it doesn't make sense for a song, or song group
	// to inherit a method they can just inherit the
	// default implementation
	// This allows me to add components
	public void add(SongComponent newSongComponent) {
		throw new UnsupportedOperationException();
	// This allows me to remove components
		public void remove(SongComponent newSongComponent) {
			throw new UnsupportedOperationException();
	// This allows me to get components
	public SongComponent getComponent(int componentIndex) {
		throw new UnsupportedOperationException();
	// This allows me to retrieve song names
	public String getSongName() {
		throw new UnsupportedOperationException();
	// This allows me to retrieve band names
	public String getBandName() {
		throw new UnsupportedOperationException();
	// This allows me to retrieve release year
	public int getReleaseYear() {
		throw new UnsupportedOperationException();
	// When this is called by a class object that extends
	// SongComponent it will print out information
	// specific to the Song or SongGroup
	public void displaySongInfo() {
		throw new UnsupportedOperationException();


import java.util.ArrayList;
import java.util.Iterator;

public class SongGroup extends SongComponent {
	// Contains any Songs or SongGroups that are added
	// to this ArrayList
	ArrayList songComponents = new ArrayList();
	String groupName;
	String groupDescription;
	public SongGroup(String newGroupName, String newGroupDescription){
		groupName = newGroupName;
		groupDescription = newGroupDescription;
	public String getGroupName() { return groupName; }
	public String getGroupDescription() { return groupDescription; }
	public void add(SongComponent newSongComponent) {
	public void remove(SongComponent newSongComponent) {
	public SongComponent getComponent(int componentIndex) {
		return (SongComponent)songComponents.get(componentIndex);
	public void displaySongInfo(){
		System.out.println(getGroupName() + " " +
				getGroupDescription() + "\n");
		// Cycles through and prints any Songs or SongGroups added
		// to this SongGroups ArrayList songComponents
		Iterator songIterator = songComponents.iterator();
		while(songIterator.hasNext()) { 
			SongComponent songInfo = (SongComponent);


public class Song extends SongComponent {
	String songName;
	String bandName;
	int releaseYear;
	public Song(String newSongName, String newBandName, int newReleaseYear){
		songName = newSongName;
		bandName = newBandName;
		releaseYear = newReleaseYear;
	public String getSongName() { return songName; }
	public String getBandName() { return bandName; }
	public int getReleaseYear() { return releaseYear; }
	public void displaySongInfo(){
		System.out.println(getSongName() + " was recorded by " +
				getBandName() + " in " + getReleaseYear());


public class DiscJockey{
	SongComponent songList;
	// newSongList contains every Song, SongGroup,
	// and any Songs saved in SongGroups
	public DiscJockey(SongComponent newSongList){
		songList = newSongList;
	// Calls the displaySongInfo() on every Song
	// or SongGroup stored in songList
	public void getSongList(){


public class SongListGenerator {
	public static void main(String[] args){
		SongComponent industrialMusic = 
				new SongGroup("Industrial", 
						"is a style of experimental music that draws on transgressive and provocative themes");
		SongComponent heavyMetalMusic = 
				new SongGroup("\nHeavy Metal", 
						"is a genre of rock that developed in the late 1960s, largely in the UK and in the US");
		SongComponent dubstepMusic = 
				new SongGroup("\nDubstep", 
						"is a genre of electronic dance music that originated in South London, England");
		// Top level component that holds everything
		SongComponent everySong = new SongGroup("Song List", "Every Song Available");
		// Composite that holds individual groups of songs
		// This holds Songs plus a SongGroup with Songs
		industrialMusic.add(new Song("Head Like a Hole", "NIN", 1990));
		industrialMusic.add(new Song("Headhunter", "Front 242", 1988));
		dubstepMusic.add(new Song("Centipede", "Knife Party", 2012));
		dubstepMusic.add(new Song("Tetris", "Doctor P", 2011));
		// This is a SongGroup that just holds Songs
		heavyMetalMusic.add(new Song("War Pigs", "Black Sabath", 1970));
		heavyMetalMusic.add(new Song("Ace of Spades", "Motorhead", 1980));
		DiscJockey crazyLarry = new DiscJockey(everySong);

24 Responses to “Composite Design Pattern Tutorial”

  1. Ellle says:

    This website rocks! There is so much good information here. Thanks for making JAVA easy to understand!

  2. boris says:

    thank you very much!

  3. Ally says:

    line 29 of SongListGenerator: industrialMusic.add(dubstepMusic);
    should this read everySong.add(dubstepMusic);?

    these are awesome – i dont know what i’d do without your videos

    • Derek Banas says:

      Thank you πŸ™‚ No, industrialMusic.add(dubstepMusic) is correct. I may have confused you because I considered DubStep to be a version of industrial. That may not be true. I don’t know because I’m definitely not a music expert

  4. Hadar says:

    Hi Derek

    And thanks for the great tutorials

    I have a Q: How come a β€œthrows” statement, is not required from methods of the abstract class SongComponent ?

  5. Pedrito says:

    Dude, I’m from Chile. You’re helping the entire world with your vids. How awesome is that?
    Take care bro and thanks

  6. Duggs says:

    awsume tutorial man!! u rock thnk u very mch

  7. Idan says:

    Great stuff!
    Thank you very much for these videos. I learn a lot.

  8. Dylan says:

    This is awesome, great work you did with these tutorials πŸ™‚

    Keep it on !

  9. nizam says:

    Great work !. Thank you very much for the tutorials πŸ™‚
    learning a lot !.

  10. Mojo Jojo says:

    Great work! Thank you!

    I know it can be many leaf classes, as long as they implement the same interface. What is not clear to me is if can it be many composite classes. It’s ok to have different ways of grouping composite/leaf objects? Can you think of an example? (I can’t πŸ˜› )

  11. Varun Risbud says:

    Hi Derek,

    Really nice tutorial. This explains the Pattern and code so well. Thanks a lot!

    Thanks & Regards,

  12. Rafael Angelo says:

    I’m from Brasil and your video help me a lot in my work school. Thank you.

  13. Thiago F. Oliveira says:

    Hey Derek, first of all, thank you so much.
    But, i’m a little bit confused with this pattern.
    Can you create a UML Class Diagram with this example and with an UML Object Diagram? Cause I don’t know how to represents “Heavey Metal” “Industrial” and “Dubstep” in the diagram.
    Thanks one more time!



  1. Design Patterns Cheat Sheet by Richard Sumilang - […] Composite Design Pattern:Β Allows you to attach individual objects and a composition of objects uniformly. For example, imagine a folder…

Leave a Reply

Your email address will not be published.