1、定义
组合模式:将对象组成树形结构以表示“整体-部分”的层次结构
写法
//目录抽象类
public abstract class Dir {
private String name;
protected List<Dir> dirs = new ArrayList<>( );
public Dir(String name){
this.name = name;
}
public abstract void addDir(Dir dir);
public abstract void rmDir(Dir dir);
public abstract void clear();
public abstract void print();
public abstract List<Dir> getFiles();
public String getName(){
return name;
}
}
public class File extends Dir{
public File(String name) {
super(name);
}
@Override
public void addDir(Dir dir) {
throw new UnsupportedOperationException("文件对象不支持该操作!");
}
@Override
public void rmDir(Dir dir) {
throw new UnsupportedOperationException("文件对象不支持该操作!");
}
@Override
public void clear() {
throw new UnsupportedOperationException("文件对象不支持该操作!");
}
@Override
public void print() {
System.out.print(getName());
}
@Override
public List<Dir> getFiles() {
throw new UnsupportedOperationException("文件对象不支持该操作!");
}
}
public class Folder extends Dir{
public Folder(String name) {
super( name );
}
@Override
public void addDir(Dir dir) {
dirs.add( dir );
}
@Override
public void rmDir(Dir dir) {
dirs.remove( dir );
}
@Override
public void clear() {
dirs.clear();
}
@Override
public void print() {
System.out.print(getName() + "(");
Iterator<Dir> iter = dirs.iterator();
while (iter.hasNext()) {
Dir dir = iter.next();
dir.print();
if(iter.hasNext()){
System.out.print(", ");
}
}
System.out.print(")");
}
@Override
public List<Dir> getFiles() {
return dirs;
}
}
public class TestMain {
/**
* 组合模式表示 : 整体-部分的关系
* @param args 树型结构
*/
public static void main(String[] args) {
//构造一个目录对象表示C盘根目录
Dir diskC = new Folder("C");
//C盘根目录下有一个文件Log.txt
diskC.addDir(new File("Log.txt"));
//C盘根目录下有三个目录Windows、PerfLogs、Program File
Dir dirWin = new Folder("Windows");
//Windows目录下有文件explorer.exe
dirWin.addDir(new File("explorer.exe"));
diskC.addDir(dirWin);
//打印出文件结构
diskC.print();
}
}