1.定义
Composite模式也叫组合模式,是构造型的设计模式之一。通过递归手段来构造树形的对象结构,并通过一个对象来访问整个对象树。
2.组合模式的结构
3.组合模式的角色和职责
Component(树形结构的节点抽象)
- 为所有的对象定义统一的接口(公共属性,行为等的定义)
- 提供管理子节点对象的接口方法
- 【可选】提供管理父节点的接口方法
Leaf(树形结构的叶节点),Component的实现子类
Composite(树形结构的枝节点),Component的实现子类
4.代码演示
package test.com.composite;import java.util.List;/* * Component--树形结构的节点抽象 */public interface IFile { //显示目录或文件的名称 public void display(); //添加 public boolean add(IFile file); //删除 public boolean remove(IFile file); //获取子节点 public ListgetChild();}
package test.com.composite;import java.util.ArrayList;import java.util.List;/* * Composite--树形结构的枝节点 */public class Folder implements IFile { private String name; private Listchildren; public Folder(String name) { this.name = name; this.children = new ArrayList (); } @Override public void display() { System.out.println(name); } @Override public boolean add(IFile file) { return children.add(file); } @Override public boolean remove(IFile file) { return children.remove(file); } @Override public List getChild() { return children; }}
package test.com.composite;import java.util.List;/* * Leaf--树形结构的叶节点 */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 boolean add(IFile file) { return false; } @Override public boolean remove(IFile file) { return false; } @Override public ListgetChild() { return null; }}
package test.com.composite;import java.util.List;/* * 测试类 */public class Main { public static void main(String[] args) { IFile rootFolder = new Folder("c:"); IFile oneFolder = new Folder("oneFolder"); IFile oneFile = new File("oneFile.text"); rootFolder.add(oneFolder); rootFolder.add(oneFile); IFile twoFolder = new Folder("twoFolder"); IFile twoFile = new File("twoFile.text"); oneFolder.add(twoFolder); oneFolder.add(twoFile); displayTree(rootFolder, 0); } public static void displayTree(IFile rootFolder, int deep) { rootFolder.display(); Listlist = rootFolder.getChild(); for(int i = 0; i < list.size(); i++) { IFile file = list.get(i); for(int j = 0; j <= deep; j++) { System.out.print("--"); } if(file instanceof File) { file.display(); } else { displayTree(file, deep+1); } } }}