首页 > 学院 > 开发设计 > 正文

设计模式——组合模式

2019-11-08 00:02:01
字体:
来源:转载
供稿:网友

组合模式就是将对象组合成树形结构以表示”部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。组合模式的核心包括抽象构件、叶子构件和容器构件。抽象构件角色:定义了叶子构件和容器构件的共同点。叶子构件角色:无子节点。容器构件角色:有容器特征,可以包含子节点。看了下面的图大家就明白什么是容器和叶子了。 这里写图片描述 组合模式的适用性 1.你想表示对象的部分-整体层次结构。 2.你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。 组合模式的工作流程 组合模式为处理树形结构提供了解决方案,描述了如何将容器和叶子进行递归组合,使得用户在使用时可以一致性的对待容器和叶子。 当容器对象的指定方法被调用时,将遍历整个树形结构,寻找包含这个方法的成员并调用执行。其中使用的就是递归调用的基址对整个树形结构进行处理的。 我们手机或电脑上面的文件夹就是最好的案例。 这里写图片描述 下面我们就以文件夹和图片来实现一个案例。

public abstract class File{ PRivate String name; public abstract void findPhoto(String name); public String getName() { return name; } public void setName(String name) { this.name = name; } public abstract void add(File file); public abstract void remove(File file); }/** * PhotoFile代表的就是叶子 */class PhotoFile extends File { public PhotoFile(String name) { super(); setName(name);} @Override public void findPhoto(String name) { System.out.println("努力查找"+name+"中~~~"); } @Override public void add(File file) { } @Override public void remove(File file) { }}/** *Folder代表的就是容器 */class Folder extends File {private List<File>fileList = new ArrayList<File>();File file; public File getFile() { return file;}public void setFile(File file) { this.file = file;} public Folder(String name) { super(); setName(name);} public void add(File file){ fileList.add(file); }public void remove(File file){ fileList.remove(file);}/** * 下面的findPhoto这个方法用到了递归 */ @Override public void findPhoto(String name) { for(File file:fileList){ file.findPhoto(name); setFile(file); } if (file.getName().equals(name)) { System.out.println("已经找到"+name+"这张图片了"); } }}

测试代码

Folder photoFolder; File photoFile1; File photoFile2; File photoFile3; File photoFile4; File photoFile5; File photoFile6; photoFolder = new Folder("图片"); photoFile1 = new PhotoFile("file1.png"); photoFile2 = new PhotoFile("file2.png"); photoFile3 = new PhotoFile("file3.png"); photoFile4 = new PhotoFile("file4.png"); photoFile5 = new PhotoFile("file5.png"); photoFile6 = new PhotoFile("file6.png"); photoFolder.add(photoFile1); photoFolder.add(photoFile2); photoFolder.add(photoFile3); photoFolder.add(photoFile4); photoFolder.add(photoFile5); photoFolder.add(photoFile6); String name = "file6.png"; photoFolder.findPhoto(name);

运行效果 这里写图片描述 组合模式到此已经结束,如有问题还请留言。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表