1、什么是组合模式
- Composite模式也叫组合模式,是构造型的设计模式之一。通过递归手段来构造树形的对象结构,并可以通过一个对象来访问整个对象树。
2、组合模式的结构
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ed304805fb42a775a4a382e3307a35c6.png)
3、组合模式的角色和职责
- Component (树形结构的节点抽象)
- 为所有的对象定义统一的接口(公共属性,行为等的定义)
- 提供管理子节点对象的接口方法
- [可选]提供管理父节点对象的接口方法
- Leaf (树形结构的叶节点)
- Component的实现子类
- Composite(树形结构的枝节点)
- Component的实现子类
4、代码实现
package com.example.demo01;
import java.util.List;
/**
* 文件节点抽象(是文件和目录的父类)
* @author Guardian
*
*/
public interface IFile {
//显示文件或者文件夹名称
public void display();
//添加
public boolean add(IFile file);
//移除
public boolean remove(IFile file);
//货的子节点
public List<IFile> getChild();
}
package com.example.demo01;
import java.util.List;
public class File implements IFile{
private String name;
public File(String name){
this.name = name;
}
@Override
public void display() {
System.out.println(name);
}
@Override
public List<IFile> getChild() {
return null;
}
@Override
public boolean add(IFile file) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean remove(IFile file) {
// TODO Auto-generated method stub
return false;
}
}
package com.example.demo01;
import java.util.ArrayList;
import java.util.List;
public class Folder implements IFile{
private String name;
private List<IFile> children;
public Folder(String name) {
this.name = name;
this.children = new ArrayList<IFile>();
}
@Override
public void display() {
System.out.println(name);
}
@Override
public List<IFile> getChild() {
return children;
}
@Override
public boolean add(IFile file) {
return children.add(file);
}
@Override
public boolean remove(IFile file) {
return children.remove(file);
}
}
package com.example.demo01;
import java.util.List;
import org.junit.Test;
public class MainClass {
@Test
public void test01(){
//C盘(一级目录)
Folder rootFolder = new Folder("C:");
//guardian目录(二级目录)
Folder guardianFolder = new Folder("guardian");
//guardian.txt文件
File guardianFile = new File("guardian.txt");
rootFolder.add(guardianFolder);
rootFolder.add(guardianFile);
//iguardian目录(三级目录)
Folder iguardianFolder = new Folder("iguardian");
File iguardianFile = new File("iguardian.txt");
guardianFolder.add(iguardianFolder);
guardianFolder.add(iguardianFile);
//iiguardian目录(四级目录)
Folder iiguardianFolder = new Folder("iiguardian");
File iiguardianFile = new File("iiguardian.txt");
iguardianFolder.add(iiguardianFolder);
iguardianFolder.add(iiguardianFile);
displayTree(rootFolder,0);
}
public static void displayTree(IFile rootFolder, int deep){
for (int i = 0; i < deep; i++) {
System.out.print("--");
}
//显示自身的名称
rootFolder.display();
//获得子树
List<IFile> children = rootFolder.getChild();
//遍历子树
for (IFile iFile : children) {
if (iFile instanceof File) {
for (int i = 0; i <= deep; i++) {
System.out.print("--");
}
iFile.display();
}else {
displayTree(iFile,deep+1);
}
}
}
}