Java Design Patterns – Composite pattern

If you look at the definition of this design pattern on websites like Wikipedia, you could be a little bit confused. First time when I was reading about this pattern I stopped read and I just thinking wait what, what this pattern do? After looking at practical examples I started to understand it.

In this post, you can find:

  • example situation when to use a Composite design pattern
  • Composite pattern code structure in Java
  • example how to use the Composite pattern

If your application needs to manipulate the hierarchy of objects that have various types of complexifying, you probably should use this pattern. The common example of this is the directory tree. You have directories and files. The file is written with the pattern: name + new line. Writing the directory is more complicated. After the name and new line, command display some space and then every file or directory in this directory is written with this space.

Composite pattern example in Java

In this post, I want to show you simple Composite pattern Java code. We would have something like directory tree from the above example. We have music, music has genres like rock and we have artists that play rock music. Artist has albums with songs on them. Hope you see this hierarchy that we would create. Songs are like files in the previous example.

Interface

We would implement this interface in all classes. Name that I used is from Linux command used to list directory content (just saying it, if you don’t know the Linux command line).

Classes

Very simple class, we create an object, single item and implement ls() function and print Client class property with song name (listing of Client class you can see below).

Group is also a single item like Song but it can have items in it. We have ArrayList and method to add items to it. Method ls() is more complicated as you can see, we iterate array and running ls() function on its objects.

Client class

Console output:

Composite Design Pattern output

Here, we have StringBuffer that contains a string that we working on in classes that you have seen above. And now we create objects and we add them to groups. In the end, we using method ls() on the oldest object to see our hierarchy tree.

You can find the code used in this article on my GitHub: Composite Pattern

So the composite design pattern is easy when you have some practical examples. Hence I always tell that the best way to learn design pattern is to write it in your own example because it’s hard to learn and fully understand when you depend only on theory.

Good luck!

Want more? Look at my others post about Design Patterns

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *