设计模式之组合模式

组合模式是一种结构型设计模式, 你可以使用它将对象组合成树状结构, 并且能像使用独立对象一样使用它们。

如果应用的核心模型能用树状结构表示, 在应用中使用组合模式才有价值。

组合模式结构

Java 示例代码:

import java.util.*;

public class CompositePattern {

    public static void main(String[] args) {

        // 父类名 对象名 = new 子类名();

        AbstractFile root = new Folder("root");

        AbstractFile folderA = new Folder("folderA");

        AbstractFile folderB = new Folder("folderB");

        AbstractFile fileC = new File("fileC");

        AbstractFile fileD = new File("fileD");

        AbstractFile fileE = new File("fileE");

        root.Add(folderA);

        root.Add(folderB);

        root.Add(fileC);

        folderA.Add(fileD);

        folderA.Add(fileE);

        print(root);

    }

    static void print(AbstractFile file) {

        file.printName();

        List<AbstractFile> childrenList = file.getChildren();

        if (childrenList == null) return;

        // for (对象类型 对象名 : 遍历对象)

        for (AbstractFile children : childrenList) {

            // children.printName();

            print(children);

        }

    }

}

abstract class AbstractFile {

    protected String name;

    public void printName() {

        System.out.println(name);

    }

    public abstract boolean Add(AbstractFile file);

    public abstract boolean Remove(AbstractFile file);

    public abstract List<AbstractFile> getChildren();

}

class Folder extends AbstractFile {

    private List<AbstractFile> childrenList = new ArrayList<AbstractFile>();

    public Folder(String name) {

        this.name = name;

    }

    @Override

    public boolean Add(AbstractFile file) {

        return childrenList.add(file);

    }

    @Override

    public boolean Remove(AbstractFile file) {

        return childrenList.remove(file);

    }

    @Override

    public List<AbstractFile> getChildren() {

        return childrenList;

    }

}

class File extends AbstractFile {

    public File(String name) {

        this.name = name;

    }

    @Override

    public boolean Add(AbstractFile file) {

        return false;

    }

    @Override

    public boolean Remove(AbstractFile file) {

        return false;

    }

    @Override

    public List<AbstractFile> getChildren() {

        return null;

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysh05

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值