组合模式
来源:互联网 发布:mac的onedrive在哪里 编辑:程序博客网 时间:2024/05/17 01:56
组合模式
定义:允许你将对象组合成树形来表达结构来表现“整体/部分”层次结构。组合能让用户以一致的方式处理个别对象及对象组合。
角色:
- component :是组合中对象的接口,适当情况下,实现所有类共有方法的默认行为,声明一个接口,用于管理和访问component子部件
- composite:定义具有叶节点的组件的行为
- leaf:定义叶节点的行为
- client:使用component接口操作组件行为
适用场合:
- 想表示对象的部分-整体层次结构
- 希望用户忽略组合对象与单个对象的不同,使用户一同一种方式使用组合结构中的所有对象。
好处:
- 定义了包含基本对象和组合对象的类层次结构,基本对象可以被组合成更复杂的组合对象,而这个组合对象有可以被组合。
- 简化客户代码,客户可以一直地使用组合结构和单个对象,通常用户不知道处理的是一个叶节点还是一个组合组件。
- 使得更容易增加新类型的组件, 新定义的Composite或leaf子类自动地与已有的结构和客户代码一起工作,客户程序不需要因为新的Component类而改变。
- 使你的设计变得更一般化。
- /**
- * 组件的接口
- * @author sky
- *
- */
- public abstract class FileComponent {
- public void add(FileComponent component){
- throw new UnsupportedOperationException();
- }
- public void remove(FileComponent component){
- throw new UnsupportedOperationException();
- }
- public FileComponent getChild(int index){
- throw new UnsupportedOperationException();
- }
- public String getName(){
- throw new UnsupportedOperationException();
- }
- public String getDescription(){
- throw new UnsupportedOperationException();
- }
- }
- /**
- * 组合件的组件,可以包含组件或者叶节点
- * @author sky
- *
- */
- public class FileComposite extends FileComponent {
- private String name;
- private List<FileComponent> list;
- public FileComposite(String name){
- this.name = name;
- list = new ArrayList<>();
- }
- @Override
- public void add(FileComponent component) {
- list.add(component);
- }
- @Override
- public void remove(FileComponent component) {
- list.remove(component);
- }
- @Override
- public FileComponent getChild(int index) {
- if ( index>=0&&list.size()>index ) {
- return list.get(index);
- }
- return null;
- }
- @Override
- public String getName() {
- return name;
- }
- @Override
- public String getDescription() {
- Iterator<FileComponent> iterator = list.iterator();
- StringBuffer sb = new StringBuffer();
- sb.append(name).append(":【");
- while (iterator.hasNext()) {
- sb.append(iterator.next().getDescription());
- }
- sb.append("】");
- return sb.toString();
- }
- }
- /**
- * leaf叶节点
- * @author sky
- *
- */
- public class FileLeaf extends FileComponent {
- private String name;
- public FileLeaf(String name){
- this.name = name;
- }
- @Override
- public String getName() {
- return name;
- }
- @Override
- public String getDescription() {
- return " name:"+name;
- }
- }
- /**
- * 测试代码
- * @author sky
- *
- */
- public class Test {
- public static void main(String[] args) {
- FileComponent directory = new FileComposite("目录1");
- FileComponent directory2 = new FileComposite("目录2");
- FileComponent file = new FileLeaf("book");
- directory2.add(file);
- file = new FileLeaf("mp3");
- directory2.add(file);
- directory.add(directory2);
- System.out.println(directory.getDescription());
- }
- }
- 输出:
- 目录1:【目录2:【 name:book name:mp3】】
0 0