组合模式

1. 什么是组合模式

Composite 模式也叫组合模式,是构造型的设计模式之一。通过递归手段来构造树形的对象结构,并可以通过一个对象来访问整个对象树。

2. 组合模式的结构

11_组合模式 - 图1

3. 组合模式的角色与职责

  • Component(树形结构的节点抽象)

    • 为所有的对象定义统一的接口(公共属性,行为等的定义)
    • 提供管理子节点对象的接口方法
    • 【可选】提供管理父节点对象的接口方法
  • Leaf(树形结构的叶节点)

    • Component 的实现子类
  • Composite(树形结构的枝节点)

    • Component 的实现子类

4. 代码演示

  1. public interface IFile {
  2. void display();
  3. boolean add(IFile file);
  4. boolean remove(IFile file);
  5. List<IFile> getChild();
  6. }
  1. public class File implements IFile {
  2. private final String name;
  3. public File(String name) {
  4. this.name = name;
  5. }
  6. @Override
  7. public void display() {
  8. System.out.println(name);
  9. }
  10. @Override
  11. public boolean add(IFile file) {
  12. return false;
  13. }
  14. @Override
  15. public boolean remove(IFile file) {
  16. return false;
  17. }
  18. @Override
  19. public List<IFile> getChild() {
  20. return null;
  21. }
  22. }
  1. public class Folder implements IFile {
  2. private final String name;
  3. private final List<IFile> children;
  4. public Folder(String name) {
  5. this.name = name;
  6. this.children = new ArrayList<>();
  7. }
  8. @Override
  9. public void display() {
  10. System.out.println(name);
  11. }
  12. @Override
  13. public boolean add(IFile file) {
  14. return this.children.add(file);
  15. }
  16. @Override
  17. public boolean remove(IFile file) {
  18. return this.children.remove(file);
  19. }
  20. @Override
  21. public List<IFile> getChild() {
  22. return children;
  23. }
  24. }
  1. public class Util {
  2. public static void displayTree(IFile iFile, int deep) {
  3. for (int i = 0; i < deep; i++) {
  4. System.out.print("--");
  5. }
  6. iFile.display();
  7. List<IFile> children = iFile.getChild();
  8. for (IFile file : children) {
  9. if (file instanceof File) {
  10. for (int i = 0; i <= deep; i++) {
  11. System.out.print("--");
  12. }
  13. file.display();
  14. } else {
  15. displayTree(file, deep + 1);
  16. }
  17. }
  18. }
  19. }
  1. IFile rootFolder = new Folder("C:");
  2. IFile beiFengFolder = new Folder("beifeng");
  3. IFile beiFengFile = new File("beifeng.txt");
  4. rootFolder.add(beiFengFolder);
  5. rootFolder.add(beiFengFile);
  6. IFile iBeifengFolder = new Folder("ibeifeng");
  7. IFile iBeifengFile = new File("ibeifeng.txt");
  8. beiFengFolder.add(iBeifengFolder);
  9. beiFengFolder.add(iBeifengFile);
  10. IFile iiBeifengFolder = new Folder("iibeifeng");
  11. IFile iiBeifengFile = new File("iibeifeng.txt");
  12. iBeifengFolder.add(iiBeifengFolder);
  13. iBeifengFolder.add(iiBeifengFile);
  14. Util.displayTree(rootFolder, 0);
  1. C:
  2. --beifeng
  3. ----ibeifeng
  4. ------iibeifeng
  5. ------iibeifeng.txt
  6. ----ibeifeng.txt
  7. --beifeng.txt