import java.util.ArrayList; import java.util.List; public class 组合模式 { public static void main(String[] args) { AbstractFile fileA=new File("fileA"); AbstractFile fileB=new File("fileB"); //fileA.printName(); AbstractFile folderB=new Folder("folderB"); AbstractFile folderA=new Folder("folderA"); //folderB.printName(); AbstractFile root=new Folder("root"); root.Add(fileA); root.Add(folderA); folderA.Add(fileB); folderA.Add(folderB); print(root); } static void print(AbstractFile file) { file.printName(); List<AbstractFile> list=file.getCildern(); if(list==null) return ; for(AbstractFile children : list) { //children.printName(); 错误的 print(children); } } } abstract class AbstractFile{ protected String name; public abstract boolean Add(AbstractFile file); public abstract boolean Remove(AbstractFile file); public abstract List<AbstractFile> getCildern(); public void printName() { System.out.println(name); } } class File extends AbstractFile{ public File(String name) { this.name=name; } @Override public boolean Add(AbstractFile file) { return false; } @Override public boolean Remove(AbstractFile file) { return false; } @Override public List<AbstractFile> getCildern() { return null; } } class Folder extends AbstractFile{ private List<AbstractFile> list =new ArrayList<AbstractFile>(); public Folder(String name) { this.name=name; } @Override public boolean Add(AbstractFile file) { return list.add(file); } @Override public boolean Remove(AbstractFile file) { return list.remove(file); } @Override public List<AbstractFile> getCildern() { return list; } }
运行结果
标签:return,name,组合,软件设计,AbstractFile,模式,Add,file,public From: https://www.cnblogs.com/cinan/p/17798647.html