天天看点

GOF——组合模式

主要处理树形结构,内部存在天然的递归.

interface AbstractFile {
    void killVirus();
}

class ImageFile implements AbstractFile {

    private String fileName;

    public ImageFile(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void killVirus() {
        System.out.println("ImageFile-->" + fileName);
    }
}

class TextFile implements AbstractFile {

    private String fileName;

    public TextFile(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void killVirus() {
        System.out.println("TextFile-->" + fileName);
    }
}

class VideoFile implements AbstractFile {

    private String fileName;

    public VideoFile(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void killVirus() {
        System.out.println("VideoFile-->" + fileName);
    }
}

class Folder implements AbstractFile {

    private String fileName;

    private List<AbstractFile> list = new ArrayList<>();

    public Folder(String fileName) {
        this.fileName = fileName;
    }

    public void add(AbstractFile file) {
        list.add(file);
    }

    public void remove(AbstractFile file) {
        list.remove(file);
    }

    public AbstractFile getChild(int index) {
        return list.get(index);
    }

    @Override
    public void killVirus() {
        System.out.println("Folder-->" + fileName);
        for (AbstractFile file : list) {
            file.killVirus();
        }
    }
}
           
/**
 * 组合模式
 */
public class Composite {

    public static void main(String[] args) {
        AbstractFile f1, f2, f3, f4;
        Folder f = new Folder("文件夹");

        f1 = new ImageFile("图片");
        f2 = new TextFile("文本");
        f3 = new VideoFile("视频");
        f.add(f1);
        f.add(f2);
        f.add(f3);
        f.killVirus();
    }
}