解决的问题
将对象组合成层级结构,支持一起修改。例如文件结构:Root Folder下有两个文件夹:Videos Folder和Images Folder,Videos Folder下存放视频文件,Images Folder下存放图片文件。当删除Root Folder时,会删除他里面的所有文件。
代码
File
:
package com.cong.designpattern.composite;
public interface File {
public void delete();
}
Folder
:
package com.cong.designpattern.composite;
import java.util.ArrayList;
import java.util.List;
public class Folder implements File {
private List<File> files = new ArrayList<>();
@Override
public void delete() {
for (File file : this.files) file.delete();
System.out.println("Delete folder");
}
public void add(File file) {
this.files.add(file);
}
}
Image
:
package com.cong.designpattern.composite;
public class Image implements File{
@Override
public void delete() {
System.out.println("Delete image");
}
}
Video
:
package com.cong.designpattern.composite;
public class Video implements File{
@Override
public void delete() {
System.out.println("Delete video");
}
}
Test code:
Folder imagesFolder = new Folder();
Image image = new Image();
imagesFolder.add(image);
Folder videosFolder = new Folder();
Video video = new Video();
videosFolder.add(video);
Folder rootFolder = new Folder();
rootFolder.add(imagesFolder);
rootFolder.add(videosFolder);
rootFolder.delete();