使用组合模式的场景:
把部分与整体的关系有树形结构来表示,从而使客户可以使用统一的方式处理部分对象和整体对象
组合模式核心:
抽象构件(Component)角色:定义了叶子和容器构件的共同点
叶子(Leaf)构件角色:无子节点
容器(Composite)构件角色:有容器特征,可以包含子节点
package designmode.composite;
public interface AbstractFile {
void killVirus();
}
package designmode.composite;
public abstract class FolderComposite implements AbstractFile{
public abstract void killVirus();
public abstract void add(AbstractFile a);
public abstract void remove(AbstractFile a);
public abstract AbstractFile getChild(int index);
}
package designmode.composite;
public interface FileLeaf extends AbstractFile{
void killVirus();
}
package designmode.composite.pojo;
import java.util.ArrayList;
import java.util.List;
import designmode.composite.AbstractFile;
import designmode.composite.FolderComposite;
public class Folder extends FolderComposite implements AbstractFile{
private String name;
private List<AbstractFile> list = new ArrayList<AbstractFile>();
public Folder(String name) {
this.name = name;
}
@Override
public void killVirus() {
System.out.printf("-----文件夹:%s进行查杀%n", name);
for (AbstractFile f: list) {
f.killVirus();
}
}
@Override
public void add(AbstractFile a) {
list.add(a);
}
@Override
public void remove(AbstractFile a) {
list.remove(a);
}
@Override
public AbstractFile getChild(int index) {
return list.get(index);
}
}
package designmode.composite.pojo;
import designmode.composite.FileLeaf;
public class ImageFile implements FileLeaf{
private String name;
public ImageFile(String name) {
this.name = name;
}
@Override
public void killVirus() {
System.out.printf("-----图像文件:%s进行查杀%n", name);
}
}
package designmode.composite.pojo;
import designmode.composite.FileLeaf;
public class TextFile implements FileLeaf{
private String name;
public TextFile(String name) {
this.name = name;
}
@Override
public void killVirus() {
System.out.printf("-----文本文件:%s进行查杀%n", name);
}
}
package designmode.composite.pojo;
import designmode.composite.FileLeaf;
public class VideoFile implements FileLeaf{
private String name;
public VideoFile(String name) {
this.name = name;
}
@Override
public void killVirus() {
System.out.printf("----视频文件:%s进行查杀%n", name);
}
}
package designmode.composite.test;
import designmode.composite.AbstractFile;
import designmode.composite.FolderComposite;
import designmode.composite.pojo.Folder;
import designmode.composite.pojo.ImageFile;
import designmode.composite.pojo.TextFile;
import designmode.composite.pojo.VideoFile;
public class Client {
public static void main(String[] args) {
AbstractFile f2,f3,f4,f5;
FolderComposite f1 = new Folder("我的收藏");
f2 = new ImageFile("老高的大头像.jpg");
f3 = new TextFile("hello.txt");
f1.add(f2);
f1.add(f3);
FolderComposite f11 = new Folder("电影");
f4 = new VideoFile("笑傲江湖.avi");
f5 = new VideoFile("神雕侠侣.avi");
f11.add(f4);
f11.add(f5);
f1.add(f11);
f1.killVirus();
}
}
结果:
组合模式工作流程分析:
组合模式为处理树形结构提供了完美的解决方案,描述了如何将容器和叶子进行递归组合,使得用户在使用时可以一致性的对待容器和叶子。
当容器对象的指定方法被调用时,将遍历整个树形结构,寻找也包含这个方法的成员,并调用执行。其中,使用了递归调用的机制对整个结构进行处理。