- 概念
将所有对象组合成一种树形结构,有分支节点、叶子节点,分支节点可以有自己的子节点,子节点可以是分支节点、叶子节点,可以进行增删的操作,而叶子节点不可以。比如文件夹就是一个分支节点,而文件就是一个叶子节点。用于遍历组织结构或者处理树形对象。父类引用指向派生类对象(Compoent->Document,Folder)。
- 类图
- 代码
public abstract class Component { public void add(Component component){ //新建文件夹或文件 } public void remove(Component component){ //删除文件夹或文件 } public void print(){ //打印 } public String getName(){ //名字 return null; } public String getType(){ //类型 return null; } } //文件类 叶子类 不能操作孩子 即不能有add remove public class Document extends Component { private String name; private String type; public Document(String name,String type){ this.name=name; this.type=type; } @Override public void print() { System.out.println(type+":"+name); } @Override public String getName() { return this.name; } @Override public String getType() { return this.type; } }
//文件夹类 孩子可以是文件夹也可以是文件 public class Folder extends Component{ private String name; private String type; private List<Component>components=new ArrayList<Component>(); public Folder(String name,String type){ this.name=name; this.type=type; } @Override public void add(Component component) { components.add(component); } @Override public void remove(Component component) { components.remove(component); } @Override public void print() { System.out.println(type+":"+name); for (Component component: components) { component.print(); } } @Override public String getName() { return this.name; } @Override public String getType() { return this.type; } } public class Main { public static void main(String[] args) { Folder desktop=new Folder("桌面","文件夹"); Folder c=new Folder("c:","文件夹"); Folder childFolder=new Folder("新建文件夹","文件夹"); Document d1=new Document("pig.jpg","文件"); Document d2=new Document("duck.png","文件"); childFolder.add(d1); childFolder.add(d2); c.add(childFolder); Folder d=new Folder("d:","文件夹"); Document d3=new Document("git.txt","文件"); d.add(d3); Folder e=new Folder("e:","文件夹"); desktop.add(c); desktop.add(d); desktop.add(e); desktop.print(); } }