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();
}
}
原文:https://www.cnblogs.com/baiyifengyun/p/14402926.html