组合模式

来源:互联网 发布:国内mba 知乎 编辑:程序博客网 时间:2024/06/06 23:23



package composite;/*** * 抽象组件 * @author zw * */public interface Component {void operation();}/*** * 叶子组件 * @author zw * */interface Lef extends Component{}/** * 容器组件 * @author zw * */interface Composite extends Component{void add(Component c);void remove(Component c);Component getChild(int index);}



package composite;import java.util.ArrayList;import java.util.List;/*** * 抽象构建 * @author zw * */public interface AbstractFile {void killVirus();   //杀毒}class imgFile implements AbstractFile{private String name;public imgFile(String name) {super();this.name = name;}@Overridepublic void killVirus() {System.out.println("正在对"+name+"的图像文件进行查杀...");}}class txtFile implements AbstractFile{private String name;public txtFile(String name) {super();this.name = name;}@Overridepublic void killVirus() {System.out.println("正在对"+name+"的文本文件进行查杀...");}}class Folder implements AbstractFile{private String name;//定义容器,用来存放本容器下构建的子节点List<AbstractFile> list =new ArrayList<AbstractFile>();public Folder(String name) {super();this.name = name;}public  void add(AbstractFile file) {list.add(file);}public  void remove(AbstractFile file) {list.remove(file);}public AbstractFile getChild(int index) {return  list.get(index);}@Overridepublic void killVirus() {// TODO Auto-generated method stubSystem.out.println("文件夹:"+name+",正在进行查杀");for (AbstractFile file : list) {file.killVirus();}}}


package composite;public class Client {public static void main(String[] args) {AbstractFile  f1 = new imgFile("我的图片");Folder f2 = new Folder("c盘目录下");f2.add(f1);f2.killVirus();}}



组合模式并非之前的组合组合模式可以用来处理树形结构