[实验任务一]:组合模式
用透明组合模式实现教材中的“文件夹浏览”这个例子。
实验要求:
1.文件的执行不需真正实现,只需简单提示即可;
2.提交源代码;
3.注意编程规范。
public abstract class AbstractFile { public abstract void add(AbstractFile element); public abstract void remove(AbstractFile element); public abstract void display(); }
public class Client { public static void main(String a[]) { AbstractFile obj1,obj2,obj3,obj4; Folder plate1,plate2,plate3; obj1=new ImageFile("a.jpg"); obj2=new TextFile("b.txt"); plate1=new Folder("Image_Text"); plate1.add(obj1); plate1.add(obj2); obj3=new VideoFile("c.mp4"); plate2=new Folder("Image_Video"); plate2.add(obj1); plate2.add(obj3); obj4=new ImageFile("d.jpg"); plate3=new Folder("Image_Text_Video_Folder"); plate3.add(plate1); plate3.add(plate2); plate3.add(obj4); plate3.display(); } }
import java.util.*; public class Folder extends AbstractFile { private String fileName; private ArrayList<AbstractFile> fileList=new ArrayList(); public Folder(String filename) { this.fileName=new String(); this.fileName=filename; } public void add(AbstractFile element) { fileList.add(element); System.out.println("添加文件夹"); } public void remove(AbstractFile element) { fileList.remove(element); System.out.println("移动文件夹"); } public void display() { System.out.println(fileName); for(Object object:fileList) { ((AbstractFile)object).display(); } System.out.println("****文件夹显示****"); } }
public class ImageFile extends AbstractFile { private String fileName; public ImageFile(String filename) { this.fileName=new String(); this.fileName=filename; } public void add(AbstractFile element) { System.out.println("添加图片文件"); } public void remove(AbstractFile element) { System.out.println("移动图片文件"); } public void display() { System.out.print(fileName); System.out.println("图片文件"); } }
public class TextFile extends AbstractFile { private String fileName; public TextFile(String filename) { this.fileName=new String(); this.fileName=filename; } public void add(AbstractFile element) { System.out.println("添加文本文件"); } public void remove(AbstractFile element) { System.out.println("移动文本文件"); } public void display() { System.out.print(fileName); System.out.println("文本文件"); } }
public class VideoFile extends AbstractFile { private String fileName; public VideoFile(String filename) { this.fileName=new String(); this.fileName=filename; } public void add(AbstractFile element) { System.out.println("添加视频文件"); } public void remove(AbstractFile element) { System.out.println("移动视频文件"); } public void display() { System.out.print(fileName); System.out.println("视频文件"); } }
标签:void,AbstractFile,System,fileName,实验,public,out From: https://www.cnblogs.com/usadingzhen/p/17818929.html