设计模式之组合模式

概念:将对象组合成树形结构以表示"部分------整体"的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

组合模式有三个角色:

  • 抽象构件:定义公有属性和方法。
  • 叶子结点:树形结构的底层结点,没有子结点,实现抽象构件的所有操作。
  • 中间结点:叶子结点之前的结点,有子结点。

组合模式最经典的例子就是文件和文件夹结构。下面用一个这样的例子来帮助大家理解组合模式。

java 复制代码
public abstract class FileComponent {
    protected String name;
    public FileComponent(String name) {
        this.name = name;
    }
    public abstract void add(FileComponent component);
    public abstract void remove(FileComponent component);
    public abstract void display(int depth);
    public String getName() {
        return name;
    }
}

public class FileNode extends FileComponent {
    public FileNode(String name) {
        super(name);
    }
    @Override
    public void add(FileComponent component) {
        throw new UnsupportedOperationException("Cannot add components to a file.");
    }
    @Override
    public void remove(FileComponent component) {
        throw new UnsupportedOperationException("Cannot remove components from a file.");
    }
    @Override
    public void display(int depth) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            sb.append("--");
        }
        System.out.println(sb + name);
    }
}

public class Directory extends FileComponent {
    private List<FileComponent> children;
    public Directory(String name) {
        super(name);
        children = new ArrayList<>();
    }
    @Override
    public void add(FileComponent component) {
        children.add(component);
    }
    @Override
    public void remove(FileComponent component) {
        children.remove(component);
    }
    @Override
    public void display(int depth) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            sb.append("--");
        }
        System.out.println(sb + name);
        for (FileComponent child : children) {
            child.display(depth + 1);
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        Directory root = new Directory("Root");
        Directory documents = new Directory("Documents");
        Directory pictures = new Directory("Pictures");
        FileNode readme = new FileNode("Readme.txt");
        FileNode image = new FileNode("image.jpg");
        root.add(documents);
        root.add(pictures);
        documents.add(readme);
        pictures.add(image);
        System.out.println("File structure:");
        root.display(0);
    }
}
相关推荐
贱贱的剑4 小时前
2.单例模式
单例模式·设计模式
Your易元6 小时前
设计模式-模板方法模式
java·设计模式·模板方法模式
暴走的海鸽9 小时前
存储库模式赋能 Django:让你的代码不那么业余,更具生命力
python·设计模式·django
小张在编程10 小时前
Java设计模式实战:备忘录模式与状态机模式的“状态管理”双雄
java·设计模式·备忘录模式
小小寂寞的城1 天前
JAVA观察者模式demo【设计模式系列】
java·观察者模式·设计模式
花好月圆春祺夏安1 天前
基于odoo17的设计模式详解---备忘模式
数据库·设计模式
DKPT1 天前
Java设计模式之行为型模式(责任链模式)介绍与说明
java·笔记·学习·观察者模式·设计模式
使一颗心免于哀伤1 天前
《设计模式之禅》笔记摘录 - 6.原型模式
笔记·设计模式
ffcf2 天前
设计模式—专栏简介
设计模式
tianchang2 天前
SSR 深度解析:从原理到实践的完整指南
前端·vue.js·设计模式