组合模式(Composite)
定义
将对象组合成树形结构以表示"部分-整体"的层次结构。
使用场景
- 当你的程序结构有类似树一样的层级关系时,例如文件系统,视图树,公司组织架构等等
- 当你要以统一的方式操作单个对象和由这些对象组成的组合对象的时候。
主要角色
- Component(组件)
- Leaf(叶子节点)
- Composite(组合节点)
类图
示例代码
安全模式
java
public interface FileSystemComponent {
void display();
}
java
public class File implements FileSystemComponent {
private final String name;
public File(String name) {
this.name = name;
}
@Override
public void display() {
System.out.println("File: " + name);
}
}
java
public class Folder implements FileSystemComponent {
private final String name;
private final List<FileSystemComponent> components;
public Folder(String name) {
this.name = name;
this.components = new ArrayList<>();
}
public void addComponent(FileSystemComponent component) {
components.add(component);
}
@Override
public void display() {
System.out.println("Folder: " + name);
for (FileSystemComponent component : components) {
component.display();
}
}
}
java
public class Client {
public static void main(String[] args) {
// 创建文件和文件夹
File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
Folder folder1 = new Folder("Folder 1");
Folder folder2 = new Folder("Folder 2");
// 组合节点包含叶子节点
folder1.addComponent(file1);
folder1.addComponent(file2);
// 组合节点包含另一个组合节点
folder2.addComponent(folder1);
// 显示整个文件系统结构
folder2.display();
}
}
java
Folder: Folder 2
Folder: Folder 1
File: file1.txt
File: file2.txt
透明模式
java
public interface FileSystemComponent {
void display();
void addComponent(FileSystemComponent component);
}
java
public class File implements FileSystemComponent {
private final String name;
public File(String name) {
this.name = name;
}
@Override
public void display() {
System.out.println("File: " + name);
}
@Override
public void addComponent(FileSystemComponent component) {
throw new UnsupportedOperationException(this.name + "是文件,不支持添加");
}
}
java
public class Folder implements FileSystemComponent {
private final String name;
private final List<FileSystemComponent> components;
public Folder(String name) {
this.name = name;
this.components = new ArrayList<>();
}
public void addComponent(FileSystemComponent component) {
components.add(component);
}
@Override
public void display() {
System.out.println("Folder: " + name);
for (FileSystemComponent component : components) {
component.display();
}
}
}
java
public class Client {
public static void main(String[] args) {
// 创建文件和文件夹
FileSystemComponent file1 = new File("file1.txt");
FileSystemComponent file2 = new File("file2.txt");
FileSystemComponent folder1 = new Folder("Folder 1");
FileSystemComponent folder2 = new Folder("Folder 2");
// 组合节点包含叶子节点
folder1.addComponent(file1);
folder1.addComponent(file2);
// 组合节点包含另一个组合节点
folder2.addComponent(folder1);
// 显示整个文件系统结构
folder2.display();
}
}