实验10:组合模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解组合模式的动机,掌握该模式的结构;
2、能够利用组合模式解决实际问题。
[实验任务一]:组合模式
用透明组合模式实现教材中的“文件夹浏览”这个例子。
实验要求:
类图
源代码
1、AbstractFile.java
package org.example.shiyanshi;
public abstract class AbstractFile {
public abstract void add(AbstractFile element);
public abstract void remove(AbstractFile element);
public abstract void display();
}
2、TextFile.java
package org.example.shiyanshi;
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("add TextFile");
}
public void remove(AbstractFile element){
System.out.println("remove TextFile");
}
public void display(){
System.out.println(fileName);
System.out.println(" TextFile");
}
}
3、VideoFile.java
package org.example.shiyanshi;
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("add VideoFile");
}
public void remove(AbstractFile element){
System.out.println("remove VideoFile");
}
public void display(){
System.out.println(fileName);
System.out.println(" VideoFile");
}
}
4、ImageFile.java
package org.example.shiyanshi;
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("add ImageFile");
}
public void remove(AbstractFile element){
System.out.println("remove ImageFile");
}
public void display(){
System.out.println(fileName);
System.out.println(" ImageFile");
}
}
5、Folder.java
package org.example.shiyanshi;
import java.util.ArrayList;
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("add Folder");
}
public void remove(AbstractFile element){
fileList.remove(element);
System.out.println("remove Folder");
}
public void display(){
System.out.println(fileName);
for(Object object:fileList){
((AbstractFile)object).display();
}
System.out.println("****Folder display****");
}
}
6、Client.java
package org.example.shiyanshi;
public class Client {
public static void main(String[] args) {
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();
}
}
运行结果截图