用透明组合模式实现教材中的“文件夹浏览”这个例子。
public abstract class AbstractFile
{
public abstract void add(AbstractFile element);
public abstract void remove(AbstractFile element);
public abstract void display();
}
import java.util.ArrayList;
public class Folder extends AbstractFile
{
private ArrayList<AbstractFile> fileList = new ArrayList<>();
private String fileName;
public Folder(String fileName)
{
this.fileName = fileName;
}
/**
* 添加文件
*/
@Override
public void add(AbstractFile element)
{
fileList.add(element);
// 获取类的简单名称
String elementName = element.getClass().getSimpleName();
//输出提示信息
System.out.println(fileName + "添加了一个" + elementName);
}
/**
* 删除文件
*/
@Override
public void remove(AbstractFile element)
{
fileList.remove(element);
// 获取类的简单名称
String elementName = element.getClass().getSimpleName();
//输出提示信息
System.out.println(fileName + "删除了一个" + elementName);
}
/**
* 递归打印文件夹里的内容
*/
@Override
public void display()
{
System.out.println(fileName);
System.out.println("-------" + fileName + "包括-------");
for (AbstractFile object : fileList)
{
object.display();
}
}
}
public class ImageFile extends AbstractFile
{
private String fileName;
public ImageFile(String fileName)
{
this.fileName = fileName;
}
@Override
public void add(AbstractFile element)
{
System.out.println("add ImageFile");
}
@Override
public void remove(AbstractFile element)
{
System.out.println("remove ImageFile");
}
@Override
public void display()
{
System.out.print(fileName);
System.out.println(" ImageFile");
}
}
public class TextFile extends AbstractFile
{
private String fileName;
public TextFile(String fileName)
{
this.fileName = fileName;
}
@Override
public void add(AbstractFile element)
{
System.out.println("add TextFile");
}
@Override
public void remove(AbstractFile element)
{
System.out.println("remove TextFile");
}
@Override
public void display()
{
System.out.print(fileName);
System.out.println(" TextFile");
}
}
public class VideoFile extends AbstractFile
{
private String fileName;
public VideoFile(String fileName)
{
this.fileName = fileName;
}
@Override
public void add(AbstractFile element)
{
System.out.println("add VideoFile");
}
@Override
public void remove(AbstractFile element)
{
System.out.println("remove VideoFile");
}
@Override
public void display()
{
System.out.print(fileName);
System.out.println(" VideoFile");
}
}
posted @
2024-11-13 09:27
涨涨涨张
阅读(
3)
评论()
编辑
收藏
举报