Composite Pattern Explained with Code and Real‑World Scenarios
This article introduces the Composite design pattern, explains its purpose of treating leaf and container objects uniformly, shows typical tree‑structured use cases, and provides a complete Java implementation with abstract component, leaf, composite, and a test demo.
What is the Composite Pattern?
The pattern unifies single leaf nodes and containers that hold multiple child nodes under a common interface, allowing client code to operate on both without distinguishing between an individual element and a collection of elements.
Core Goal
To treat leaves and branches in a tree structure uniformly, simplifying code for operations such as copy, delete, or display.
Typical Real‑World Scenarios
File systems: files (leaves) and folders (containers) both support copy and delete.
Backend side‑menu trees, organizational charts, product category hierarchies.
Permission menus, multi‑level comments, geographic region trees.
Java Implementation (File System Example)
1. Abstract Component (common contract for file and folder)
public abstract class FileComponent {
protected String name;
public FileComponent(String name){
this.name = name;
}
// common print method
public abstract void show();
// folder‑only operations; leaf provides empty implementation
public void add(FileComponent component){}
public void remove(FileComponent component){}
}2. Leaf Node – File
public class FileLeaf extends FileComponent{
public FileLeaf(String name) {
super(name);
}
@Override
public void show() {
System.out.println("文件:" + name);
}
}3. Composite Node – Folder
import java.util.ArrayList;
import java.util.List;
public class FolderComposite extends FileComponent{
private List<FileComponent> childList = new ArrayList<>();
public FolderComposite(String name) {
super(name);
}
@Override
public void add(FileComponent component) {
childList.add(component);
}
@Override
public void remove(FileComponent component) {
childList.remove(component);
}
@Override
public void show() {
System.out.println("【文件夹】" + name);
for(FileComponent child : childList){
child.show();
}
}
}4. Test Invocation
public class Test {
public static void main(String[] args) {
// leaf files
FileComponent txt = new FileLeaf("笔记.txt");
FileComponent img = new FileLeaf("图片.png");
// sub‑folder
FileComponent subFolder = new FolderComposite("素材文件夹");
subFolder.add(img);
// root folder
FileComponent root = new FolderComposite("桌面");
root.add(txt);
root.add(subFolder);
// unified printing without distinguishing file/folder
root.show();
}
}Common Business Scenarios Summary
Hierarchical data such as system menus, department structures, multi‑level product categories.
File systems, resource directories, permission trees.
Multi‑level comments, e‑commerce category trees, geographic region trees.
Any structure requiring recursive traversal with uniform add, remove, and display operations.
Tip
Leaf nodes do not need to add child elements; providing empty add/remove methods is sufficient, making the pattern ideal for trees with a fixed depth.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
liandk
Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
