package com.maom.design.D_14_Composite;
import java.util.ArrayList;
import java.util.List;
/**
* @Title: D_14_Composite
* @Description: 14_组合模式
* @Author maohb
* @Version 1.0
*/
public class D_14_Composite {
public static void main(String[] args) {
Folder rootFolder = new Folder("C:");
Folder oneFolder = new Folder("一级目录");
File oneFile = new File("一级文件.txt");
rootFolder.add(oneFolder);
rootFolder.add(oneFile);
Folder twoFolder = new Folder("二级目录");
File twoFile = new File("二级文件.txt");
oneFolder.add(twoFolder);
oneFolder.add(twoFile);
Folder threeFolder = new Folder("三级目录");
File threeFile = new File("三级文件.txt");
twoFolder.add(threeFolder);
twoFolder.add(threeFile);
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 file : children) {
if (file instanceof File) {
for (int i = 0; i <= deep; i++) {
System.out.print("--> ");
}
file.display();
}
else {
displayTree(file, deep + 1);
}
}
}
}
/** 文件节点抽象(是文件和目录的父类) */
interface IFile {
//显示文件或者文件夹的名称
public void display();
//添加
public boolean add(IFile file);
//移除
public boolean remove(IFile file);
//获得子节点
public List<IFile> getChild();
}
class File implements IFile {
private String name;
public File(String name) {
this.name = name;
}
public void display() {
System.out.println(name);
}
// 文件 不返回子节点
public List<IFile> getChild() {
return null;
}
public boolean add(IFile file) {
return false;
}
public boolean remove(IFile file) {
return false;
}
}
class Folder implements IFile{
private String name;
private List<IFile> children;
public Folder(String name) {
this.name = name;
children = new ArrayList<IFile>();
}
public void display() {
System.out.println(name);
}
// 文件夹 返回子节点
public List<IFile> getChild() {
return children;
}
public boolean add(IFile file) {
return children.add(file);
}
public boolean remove(IFile file) {
return children.remove(file);
}
}
设计模式笔记_14_组合模式
最新推荐文章于 2024-09-10 17:07:09 发布