设计模式(8):组合模式 Composite

将对象组合成树形结构以表示“部分-整体”的层次结构。“组合” 使得用户对单个对象和组合对象的使用具有一致性,对于乘积比较复杂的数据结构使用。

组合模式 composite

问题:

Application needs to manipulate a hierarchical collection of “primitive” and “composite” objects. Processing of a primitive object is handled one way, and processing of a composite object is handled differently. Having to query the “type” of each object before attempting to process it is not desirable.

意图:

例:很少用,所以能想到的场景很少,就拿windows的资源管理器来说,就是一个将文件和文件夹组合在一起的组合模式

代码1:定义需要使用的方法,如ls(window应该叫dir才对^_^),并定义一个文件子类

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
package com.xdnote.DesignPattern.structural.bridge;

public abstract class Prize {

private String name = "";

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public abstract boolean validate();

@Override
public String toString() {
return this.name.equals("")?"哎,什么都没中":"恭喜您中得"+this.name;
}

}

public class File extends Composite{

private String name;

public File(String name){
this.name=name;
}
@Override
public void ls() {
System.out.println(Client.limit+this.name);
}
}

代码二:定义文件夹,加入组合方法

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
package com.xdnote.DesignPattern.structural.composite;

import java.util.ArrayList;
import java.util.List;

public class Dir extends Composite{

private String name;
private List<Composite> fileList=new ArrayList<Composite>();
public void add(Composite o){
this.fileList.add(o);
}
public Dir(String name){
this.name=name;
}
@Override
public void ls() {
System.out.println(Client.limit+this.name);
Client.limit.append(" ");
if(this.fileList.size()>0){
for(int i=0;i<this.fileList.size();i++){
this.fileList.get(i).ls();
}
}
Client.limit.setLength(Client.limit.length()-3);
}
}

代码三:客户端使用

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
	public static void main(String[] args) {
Dir one = new Dir(“文件夹A“),
two = new Dir("文件夹B"),
thr = new Dir("文件夹C");
File a = new File("文件A"),
b = new File("文件B"),
c = new File("文件C"),
d = new File("文件D"),
e = new File("文件E");
one.add(a);
one.add(two);
one.add(b);
two.add(c);
two.add(d);
two.add(thr);
thr.add(e);
one.ls();

/**
*
*
dir111
a
dir222
c
d
dir333
e
b
*/
}

小结

组合模式 composite