11.5实验10:组合模式
[实验任务一]:组合模式
用透明组合模式实现教材中的“文件夹浏览”这个例子。
实验要求:
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();
}
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/836000.html
如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!