Composite Pattern
Learn how to treat a single object and a whole group of objects in the same way, using folders and files, and why tree structures and recursion make this pattern so natural.
Think about the folders on your computer. A folder can contain files, and it can also contain other folders, which contain more files and folders, and so on. Now someone asks: "How big is this folder?" You do not care whether it contains five files or fifty nested folders. The answer is simply "the sum of everything inside". A single file has a size, and a folder has a size, and you ask both the same question: "what is your size?"
That is the idea behind the Composite pattern. It is used when you have a tree-shaped structure of parts and wholes, and you want to treat one item and a group of items in the same way. It is the last pattern of the structural group.
01The problem: files and folders are different, but should feel the same
Suppose you write a program that calculates folder sizes. A first attempt, with two separate classes and no shared idea, might look like this:
long totalSize(Object item) {
if (item instanceof FileItem) {
return ((FileItem) item).getSizeInKb();
} else if (item instanceof FolderItem folder) {
long total = 0;
for (Object child : folder.getChildren()) {
total += totalSize(child); // the same check again and again
}
return total;
}
throw new IllegalArgumentException("Unknown item");
}This works, but every operation you add (size, print, search, delete, count files) needs the same instanceof checks and the same loop. If you add a new kind of item, such as a shortcut, you must edit every one of these methods. The code that uses the items must know how they are built.
We want the caller to say item.sizeInKb() and not care whether item is a file or a folder.
Loading the rest of the lesson…