设计模式-组合模式

组合模式

有时又叫作部分-整体模式,将对象组合成树状的层次结构的模式,用来表示“部分-整体”的关系,使用户对单个对象和组合对象具有一致的访问性。

优点

1. 组合模式使得客户端代码可以一致地处理单个对象和组合对象,无须关心自己处理的是单个对象,还是组合对象,这简化了客户端代码;

2. 更容易在组合体内加入新的对象,客户端不会因为加入了新的对象而更改源代码,满足“开闭原则”;

缺点

1.设计较复杂,客户端需要花更多时间理清类之间的层次关系;

2.不容易限制容器中的构件;

3.不容易用继承的方法来增加构件的新功能;

组成

1
2
3
4
5
6
7
-  '抽象构件'(Component)角色:它的主要作用是为树叶构件和树枝构件'声明公共接口,并实现它们的默认行为'。在透明式的组合模式中抽象
    构件还声明访问和管理子类的接口;在安全式的组合模式中不声明访问和管理子类的接口,管理工作由树枝构件完成。

- '树叶构件'(Leaf)角色:是组合中的叶节点对象,它没有子节点,用于'实现抽象构件角色中声明的公共接口'

- '树枝构件'(Composite)角色:是组合中的分支节点对象,它有子节点。它'实现了抽象构件角色中声明的接口',它的主要作用是存储和管理
    子部件,通常包含 Add()、Remove()、GetChild() 等方法。

分类

(1) 透明式

抽象构件声明了所有子类中的全部方法,包括add,remove等,使树叶和树枝具备完全一致的行为接口。所以客户端无须区别树叶对象和树枝对象,对客户端来说是透明的。

缺点:树叶构件本来没有 Add()、Remove() 及 GetChild() 方法,却要实现它们(空实现或抛异常),这样会带来一些安全性问题。

(2) 安全式

抽象构件不去声明add、remove方法,将管理子构件的方法移到树枝构件中,抽象构件和树叶构件没有对子对象的管理方法,这样就避免了上一种方式的安全性问题。

缺点:由于不够透明,树叶和树枝不具备相同的接口,客户端的调用需要做相应的判断带来不便。

应用场景

1.在需要表示一个对象整体与部分的层次结构的场合。

2.要求对用户隐藏组合对象与单个对象的不同,用户可以用统一的接口使用组合结构中的所有对象的场合。

Java  AWT/Swing中的简单组件 JTextComponent 有子类 JTextField、JTextArea,容器组件 Container 也有子类 Window、Panel。

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class CompositePattern
{
public static void main(String[] args)
{
Component c0=new Composite();
Component c1=new Composite();
Component leaf1=new Leaf("1");
Component leaf2=new Leaf("2");
Component leaf3=new Leaf("3");
c0.add(leaf1);
c0.add(c1);
c1.add(leaf2);
c1.add(leaf3);
c0.operation();
}
}
//抽象构件
interface Component
{
public void add(Component c);
public void remove(Component c);
public Component getChild(int i);
public void operation();
}
//树叶构件
class Leaf implements Component
{
private String name;
public Leaf(String name)
{
this.name=name;
}
public void add(Component c){ }
public void remove(Component c){ }
public Component getChild(int i)
{
return null;
}
public void operation()
{
System.out.println("树叶"+name+":被访问!");
}
}
//树枝构件
class Composite implements Component
{
private ArrayList<Component> children=new ArrayList<Component>();
public void add(Component c)
{
children.add(c);
}
public void remove(Component c)
{
children.remove(c);
}
public Component getChild(int i)
{
return children.get(i);
}
public void operation()
{
for(Object obj:children)
{
((Component)obj).operation();
}
}
}
文章目录
  1. 1. 组合模式
    1. 1.1. 优点
    2. 1.2. 缺点
    3. 1.3. 组成
    4. 1.4. 分类
      1. 1.4.1. (1) 透明式
      2. 1.4.2. (2) 安全式
    5. 1.5. 应用场景
    6. 1.6. 实现
| 139.6k