一、概念
组合模式也叫合成模式,有时又叫部分-整体模式。只要是树形结构,就要考虑使用组合模式。
二、实例
public abstract class File {
private String name;
public File(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void watch();
/**
* 组合方法
*
*/
public void add(File file){
throw new UnsupportedOperationException();
}
public void del(File file){
throw new UnsupportedOperationException();
}
public File getChild(int position){
throw new UnsupportedOperationException();
}
}
public class Folder extends File {
private List<File> fileList;
public Folder(String name){
super(name);
fileList = new ArrayList<>();
}
@Override
public void watch() {
StringBuffer sb = new StringBuffer();
for (File file:fileList){
sb.append(file.getName() + ";");
}
System.out.println("组合模式:这是一个叫" + getName() + "文件夹,包含" + fileList.size() + "个文件,分别是" + sb);
}
@Override
public void add(File file){
fileList.add(file);
}
@Override
public void del(File file){
fileList.remove(file);
}
@Override
public File getChild(int position) {
return fileList.get(position);
}
}
public class TextFile extends File {
public TextFile(String name) {
super(name);
}
@Override
public void watch() {
System.out.println("组合模式:这是一个叫" + getName() + "文本文件");
}
}
public class Client {
public static void main(String[] args) {
File fileA = new TextFile("a.txt");
File fileB = new TextFile("b.txt");
Folder aking = new Folder("king");
Folder bking = new Folder("kang");
aking.add(fileA);
aking.add(fileB);
bking.add(aking);
aking.watch();
bking.watch();
}
}