组合模式(Composite Pattern)有时候又叫做部分-整体模式,它使我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以向处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。
组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
组合模式的包含角色:
(1) Component 抽象构件角色,定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性。
(2) Leaf 叶子构件,叶子对象,其下再也没有其他的分支,也就是遍历的最小单位。
(3) Composite 树枝构件,树枝对象,它的作用是组合树枝节点和叶子节点形成一个树形结构。
1、抽象构件角色
public abstract class Component {
public void operation() {
System.out.println("Component.operation()");
}
}
2、树枝构件
public class Composite extends Component {
private ArrayList<Component> componentArrayList = new ArrayList<>();
public void add(Component component) {
componentArrayList.add(component);
}
public void remove(Component component) {
componentArrayList.remove(component);
}
public ArrayList<Component> getChildren() {
return this.componentArrayList;
}
}
3、树叶构件
public class Leaf extends Component {
@Override
public void operation() {
System.out.println("Leaf.operation()");
}
}
4、组合模式的使用
public class CompositeMain {
public static void main(String[] args) {
Composite root = new Composite();
root.operation();
Composite branch = new Composite();
root.add(branch);
Leaf leaf1 = new Leaf();
Leaf leaf2 = new Leaf();
branch.add(leaf1);
branch.add(leaf2);
display(root);
}
public static void display(Composite root) {
for (Component component : root.getChildren()) {
if (component instanceof Leaf) {
component.operation();
} else {
display((Composite) component);
}
}
}
}
优点:高层模块调用简单;节点自由增加。
缺点:在使用组合模式时,其叶子和树枝的声明都是实现类,而不是接口,违反了依赖倒置原则。
本文实现源码: https://github.com/wshunli/design-patterns/tree/master/src/ch11
参考资料
1、JAVA设计模式十七—Composite(组合模式) - CSDN博客
https://blog.csdn.net/hfmbook/article/details/7693069
2、Java设计模式—组合模式 - CSDN博客
https://blog.csdn.net/qq_25827845/article/details/52496522
3、组合模式 | 菜鸟教程
http://www.runoob.com/design-pattern/composite-pattern.html 如果本文对您有所帮助,且您手头还很宽裕,欢迎打赏赞助我,以支付网站服务器和域名费用。
您的鼓励与支持是我更新的最大动力,我会铭记于心,倾于博客。
本文链接: https://www.wshunli.com/posts/fb6e1df3.html