11.5實驗10:組合模式
席發表於2024-11-18
[實驗任務一]:組合模式
用透明組合模式實現教材中的“資料夾瀏覽”這個例子。
實驗要求:
1.檔案的執行不需真正實現,只需簡單提示即可;
2.提交原始碼;
3.注意程式設計規範。
public abstract class AbstractFile {
public abstract void add(AbstractFile ele);
public abstract void remove(AbstractFile ele);
public abstract void display();
}
import java.util.ArrayList;
public class Folder extends AbstractFile{
private String filename;
private ArrayList al=new ArrayList<>();
public Folder(String f) {
filename=f;
}
@Override
public void add(AbstractFile ele) {
// TODO Auto-generated method stub
al.add(ele);
System.out.println("Folder add");
}
@Override
public void remove(AbstractFile ele) {
// TODO Auto-generated method stub
al.remove(ele);
System.out.println("Folder remove");
}
@Override
public void display() {
// TODO Auto-generated method stub
for(Object object:al)
{
((AbstractFile)object).display();
}
System.out.println("Folder:display");
}
}
public class ImageFile extends AbstractFile{
private String filename;
public ImageFile(String f) {
filename=f;
}
@Override
public void add(AbstractFile ele) {
// TODO Auto-generated method stub
System.out.println("新增Image檔案");
}
@Override
public void remove(AbstractFile ele) {
// TODO Auto-generated method stub
System.out.println("刪除Image檔案");
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("展示Image檔案"+filename);
}
}
public class TextFile extends AbstractFile{
private String filename;
public TextFile(String f) {
filename=f;
}
@Override
public void add(AbstractFile ele) {
// TODO Auto-generated method stub
System.out.println("新增Text檔案");
}
@Override
public void remove(AbstractFile ele) {
// TODO Auto-generated method stub
System.out.println("刪除Text檔案");
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("展示Text檔案"+filename);
}
}
public class VideoFile extends AbstractFile{
private String filename;
public VideoFile(String f) {
filename=f;
}
@Override
public void add(AbstractFile ele) {
// TODO Auto-generated method stub
System.out.println("新增Video檔案");
}
@Override
public void remove(AbstractFile ele) {
// TODO Auto-generated method stub
System.out.println("刪除Video檔案");
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("展示Video檔案"+filename);
}
}
public class Client {
public static void main(String a[])
{
AbstractFile obj1,obj2,obj3,obj4,obj5;
Folder plate1,plate2,plate3;
obj1=new ImageFile("aaa.png");
obj2=new TextFile("bbb.txt");
plate1=new Folder("ccc");
plate1.add(obj1);
plate1.add(obj2);
obj3=new VideoFile("ddd.mp3");
obj4=new VideoFile("eee.mp3");
plate2=new Folder("fff");
plate2.add(obj3);
plate2.add(obj4);
obj5=new ImageFile("ggg.jpg");
plate3=new Folder("hhh");
plate3.add(plate1);
plate3.add(plate2);
plate3.add(obj5);
plate3.display();
}
}