组合模式-composite
唠叨:
看了三本书,都是文件夹和文件的例子,我还是不挣扎了,其实我也想了一个例子(公司的组织架构)。当写代码的时候遇见树形结构的数据,都应该想起这个模式。
类图:
伪代码:
/**
* @author 康康的远方
* @date 2021/4/9
*/
public abstract class Entry {
public abstract String getName();
public abstract int getSize();
public void addEntry(Entry entry) {
throw new RuntimeException("不能添加文件");
}
public abstract void print(String prefix);
@Override
public String toString(){
return getName()+"("+getSize()+")";
}
}
/**
* @author 康康的远方
* @date 2021/4/9
*/
public class File extends Entry {
private String name;
private int size;
public File(String name, int size) {
this.name = name;
this.size = size;
}
@Override
public String getName() {
return this.name;
}
@Override
public int getSize() {
return this.size;
}
@Override
public void print(String prefix) {
}
}
/**
* @author 康康的远方
* @date 2021/4/9
*/
public class Directory extends Entry {
private List<Entry> entryList = new ArrayList<>();
private String name;
public Directory(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name;
}
@Override
public int getSize() {
return 0;
}
@Override
public void print(String prefix) {
Iterator<Entry> iterator = entryList.iterator();
while (iterator.hasNext()) {
Entry next = iterator.next();
System.out.println(prefix + "/" + next);
next.print(prefix+"/"+next.getName());
}
}
@Override
public void addEntry(Entry entry) {
this.entryList.add(entry);
}
}
public class CompositeTest {
public static void main(String[] args) {
Directory d = new Directory("D");
Directory movies = new Directory("movies");
Directory books = new Directory("books");
d.addEntry(movies);
d.addEntry(books);
File movie1 = new File("这个杀手不太冷.MP4", 1024);
File movie2 = new File("大话西游.MP4", 1024);
File movie3 = new File("色即是空.avi", 2048);
movies.addEntry(movie1);
movies.addEntry(movie2);
movies.addEntry(movie3);
File book1 = new File("金瓶梅.txt", 500);
File book2 = new File("西厢记.txt", 600);
books.addEntry(book1);
books.addEntry(book2);
//电影文件夹里面有个隐藏文件,你懂的
Directory secret = new Directory("secret");
File file = new File("泷泽萝拉.avi", 3096);
movies.addEntry(secret);
secret.addEntry(file);
d.print(d.getName());
}
}
------------------打印输出--------------------------
D/movies(0)
D/movies/这个杀手不太冷.MP4(1024)
D/movies/大话西游.MP4(1024)
D/movies/色即是空.avi(2048)
D/movies/secret(0)
D/movies/secret/泷泽萝拉.avi(3096)
D/books(0)
D/books/金瓶梅.txt(500)
D/books/西厢记.txt(600)
总结:
组合模式适合树结构的数据。