组合模式(结构型)

定义

  1. 将单个对象和组合对象用相同的接口进行表示
  2. 使单个对象和组合对象保持一致的处理方式

适用场景

  1. 希望客户端可以忽略单个对象的组合对象的差异时
  2. 对象层次具备整体和部分,呈树型结构

实例

public abstract class Directory {
    public String name;

    public Directory(String name) {
        this.name = name;
    }

    protected abstract void show();
}

public class Folder extends Directory {
    // 使用同一Directory
    // 通过level控制层级关系
    private Integer level;
    private List<Directory> dirs;

    public Folder(String name,int level) {
        super(name);
        this.level = level;
        this.dirs = new ArrayList<Directory>();
    }

    @Override
    protected void show() {
        System.out.println(this.name);

        for (Directory dir: dirs) {
            if (level != null) {
                for (int i = 0; i < level; i++) {
                    System.out.print("  ");
                }
                for (int i = 0; i < level; i++) {
                    if (i == 0) {
                        System.out.print("+");
                    }
                    System.out.print("-");
                }
            }
            dir.show();
        }
    }

    public boolean add(Directory directory) {
        return this.dirs.add(directory);
    }

    public boolean remove(Directory directory) {
        return this.dirs.remove(directory);
    }

}


public class File extends Directory {

    public File(String name) {
        super(name);
    }

    @Override
    protected void show() {
        System.out.println(this.name);
    }
}

public class Test {
    public static void main(String[] args) {
        File qq = new File("qq.exe");
        File wx = new File("wx.exe");

        Folder office = new Folder("办公软件",3);
        File word = new File("word.exe");
        File excel = new File("excel.exe");
        File ppt = new File("ppt.exe");
        office.add(word);
        office.add(excel);
        office.add(ppt);

        Folder root = new Folder("D盘",2);
        root.add(qq);
        root.add(wx);
        root.add(office);

        Folder windows = new Folder("windows",1);
        windows.add(root);
        windows.show();
    }
}

应用

  1. Hashmap - putAll
  2. Arraylist - addAll
  3. Mybatis - sqlNode

两种模式

  1. 透明模式
    1. 最顶层的抽象类个体和组合的方法都在其中
    2. 个体和组合继承后都具备其中的方法,叶子节点不具备的,也包含在其中
    3. 违背最少知道原则
    4. 最顶层可使用new unsupportedoperationexception()
  2. 安全模式
    1. 最顶层的抽象类只定义所有节点都具备的方法
    2. 自己独有的只定义在自己的类里面
    3. 满足最少知道原则
  3. 组合模式不一定是树型结构

优点

  1. 清楚的定义了复杂层次的复杂对象,表示对象的全部或者部分层次
  2. 让客户端忽略层次的差异,方便对整个层次结构进行控制
  3. 符合开闭原则

缺点

  1. 限制类型时会较为复杂
  2. 使设计更为抽象
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值