需求:计算机的文件系统是一个典型的树形结构,目录包含文件夹和文件,文件夹里面又可以包含文件夹和文件。下面用代码来实现一个目录系统。
UML图设计:
代码:
package test;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IntelliJ IDEA
* User:chenweipeng
* Date:3/29/2022
* Time:2:59 PM
* Description:
*/
public abstract class Directory {
protected String name;
public Directory(String name)
{
this.name = name;
}
public abstract void show();
}
class File extends Directory{
public File(String name) {
super(name);
}
@Override
public void show() {
System.out.println(this.name);
}
}
class Folder extends Directory{
private List<Directory> dirs;
private Integer level;
public Folder(String name, Integer level) {
super(name);
this.level = level;
this.dirs = new ArrayList<Directory>();
}
@Override
public void show() {
System.out.println(this.name);
for (Directory dir:dirs){
if (this.level != null){
for (int i = 0;i<this.level;++i){
System.out.print(" ");
}
for (int i = 0;i<this.level;++i){
if (i == 0) System.out.print("+");
System.out.print("-");
}
}
dir.show();
}
}
public boolean add(Directory dir){
return this.dirs.add(dir);
}
public boolean remove(Directory dir){
return this.dirs.remove(dir);
}
public Directory get(int index){
return this.dirs.get(index);
}
public void list(){
for (Directory dir:this.dirs){
System.out.println(dir.name);
}
}
}
class Test11{
public static void main(String[] args) {
System.out.println("====================安全组合模式======================");
File qq = new File("qq.exe");
File wx = new File("wechat.exe");
Folder office = new Folder("办公软件", 2);
File word = new File("Word.exe");
File ppt = new File("PowerPoint.exe");
File excel = new File("Excel.exe");
office.add(word);
office.add(ppt);
office.add(excel);
Folder wps = new Folder("金沙软件", 2);
wps.add(new File("WPS.exe"));
office.add(wps);
Folder root = new Folder("根目录", 1);
root.add(qq);
root.add(wx);
root.add(office);
System.out.println("-------------------show()方法效果------------------");
root.show();
System.out.println("-------------------list()方法效果-------------------");
root.list();
}
}
输出:
====================安全组合模式======================
-------------------show()方法效果------------------
根目录
+-qq.exe
+-wechat.exe
+-办公软件
+--Word.exe
+--PowerPoint.exe
+--Excel.exe
+--金沙软件
+--WPS.exe
-------------------list()方法效果-------------------
qq.exe
wechat.exe
办公软件