实验10:组合模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解组合模式的动机,掌握该模式的结构;
2、能够利用组合模式解决实际问题。
[实验任务一]:组合模式
用透明组合模式实现教材中的“文件夹浏览”这个例子。
1.文件的执行不需真正实现,只需简单提示即可;
2.提交源代码;
3.注意编程规范。
package rjsj.no10;
public class Client {
public static void main(String[] args) {
AbstractFile obj1,obj2,obj3,obj4,obj5;
Folder plate1,plate2,plate3;
obj1 = new ImageFile("图片文件1");
obj2 = new TextFile("文本文件1");
plate1 = new Folder("父文件夹1");
plate1.add(obj1);
plate1.add(obj2);
obj3 = new VideoFile("视频文件1");
obj4 = new Folder("子文件夹1");
plate2 = new Folder("父文件夹2");
plate2.add(obj3);
plate2.add(obj4);
obj5 = new TextFile("文本文件2");
plate3 = new Folder("父文件夹3");
plate3.add(obj5);
plate3.add(plate1);
plate3.add(plate2);
plate3.display();
}
}
package rjsj.no10;
import java.util.ArrayList;
public class Folder extends AbstractFile{
private String fileName;
private ArrayList fileList=new ArrayList();
public Folder(String filename) {
this.fileName=new String();
this.fileName=filename;
}
@Override
public void add(AbstractFile element) {
fileList.add(element);
System.out.println("新建文件夹");
}
@Override
public void remove(AbstractFile element) {
fileList.remove(element);
System.out.println("删除文件夹");
}
@Override
public void display() {
for (Object obj:fileList){
((AbstractFile)obj).display();
}
System.out.println("打开文件夹");
}
} package rjsj.no10;
public class ImageFile extends AbstractFile{
private String fileName;
public ImageFile(String filename) {
this.fileName=new String();
this.fileName=filename;
}
@Override
public void add(AbstractFile element) {
System.out.println("添加图片文件");
}
@Override
public void remove(AbstractFile element) {
System.out.println("移除图片文件");
}
@Override
public void display() {
System.out.println(fileName);
System.out.println("打开图片文件");
}
}
package rjsj.no10;
public class TextFile extends AbstractFile{
private String fileName;
public TextFile(String filename) {
this.fileName=new String();
this.fileName=filename;
}
@Override
public void add(AbstractFile element) {
System.out.println("添加文本文件");
}
@Override
public void remove(AbstractFile element) {
System.out.println("移除文本文件");
}
@Override
public void display() {
System.out.println(fileName);
System.out.println("打开文本文件");
}
}
package rjsj.no10;
public class VideoFile extends AbstractFile{
private String fileName;
public VideoFile(String filename) {
this.fileName=new String();
this.fileName=filename;
}
@Override
public void add(AbstractFile element) {
System.out.println("添加视频文件");
}
@Override
public void remove(AbstractFile element) {
System.out.println("移除视频文件");
}
@Override
public void display() {
System.out.println(fileName);
System.out.println("播放视频文件");
}
}
package rjsj.no10;
public abstract class AbstractFile {
public abstract void add(AbstractFile element);
public abstract void remove(AbstractFile element);
public abstract void display();
}