Welcome 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

SONGCOMPONENT.JAVA

// 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();
}
}

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

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 😛 )

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!