结构型模式之组合模式

 
 
一.定义

  组合模式(Component)也叫合成模式,有时又叫做部分-整体模式,主要是用来描述部分与整体的关系。将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

二、模式结构成员构成

• Component 抽象构件角色
定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性。

•  Leaf 叶子构件
叶子对象,其下再也没有其他的分支,也就是遍历的最小单位。
•  Composite 树枝构件
树枝对象,它的作用是组合树枝节点和叶子节点形成一个树形结构。

 
三.代码示例
 1 /**
 2  * Component
 3  * 抽象构件
 4  */
 5 public abstract class Component {
 6     //个体和整体都具有的共享
 7     public void doSomething() {
 8         //编写业务逻辑
 9     }
10 } 
11 
12 /**
13  * Composite
14  * 树枝构件
15  */
16 public class Composite extends Component {
17     //构件容器
18     private ArrayList<Component> componentArrayList = new ArrayList<Component>();
19 
20     //增加一个叶子构件或树枝构件
21     public void add(Component component) {
22         this.componentArrayList.add(component);
23     }
24 
25     //删除一个叶子构件或树枝构件
26     public void remove(Component component) {
27         this.componentArrayList.remove(component);
28     }
29 
30     //获得分支下的所有叶子构件和树枝构件
31     public ArrayList<Component> getChildren() {
32         return this.componentArrayList;
33     }
34 }  
35 
36 /**
37  * Leaf
38  * 树叶构件
39  * 树叶节点是没有子下级对象的对象,定义参加组合的原始对象行为。
40  */
41 public class Leaf extends Component {
42 
43     //  可以覆写父类方法
44     @Override
45     public void doSomething() {
46 
47     }
48 }
49 
50 /**
51  * Client
52  * 测试类负责树状结构的建立,并可以通过递归方式遍历整个树。
53  */
54 public class Client {
55     public static void main(String[] args) {
56         //创建一个根节点
57         Composite root = new Composite();
58         root.doSomething();
59         //创建一个树枝构件
60         Composite branch = new Composite();
61         //创建一个叶子节点
62         Leaf leaf = new Leaf();
63         //建立整体
64         root.add(branch);
65         branch.add(leaf);
66     }
67 
68     //通过递归遍历树
69     public static void display(Composite root) {
70         for (Component c : root.getChildren()) {
71             if (c instanceof Leaf) { //叶子节点
72                 c.doSomething();
73             } else { //树枝节点
74                 display((Composite) c);
75             }
76         }
77     }
78 }  
View Code
 
 
四.优点和缺点分析
优点:
>对于客户端来说,简化了调用,对于树形结构中的所有节点都是Component,局部和整体对调用者来说没有任何区别,高层模块不必关心自己处理的是单个对象还是整个组合结构,简化了高层模块的代码。
>使用了组合模式,增加一个树枝节点、树叶节点很容易,只要找到它的父节点就成,非常容易扩展,符合开闭原则
 
缺点:
>组合模式有一个非常明显的缺点,直接使用了实现类!这在面向接口编程上是很不恰当的,与依赖倒置原则冲突,它限制了你接口的影响范围。
 
五.应用场景
> 维护和展示部分-整体关系的场景,如树形菜单、文件和文件夹管理。
> 从一个整体中能够独立出部分模块或功能的场景。

猜你喜欢

转载自www.cnblogs.com/756623607-zhang/p/9236673.html