设计模式(十三)组合模式

2019-07-08  本文已影响0人  天色将变
定义

组合模式允许你将对象组合成树形结构来表现“整体/部分”层次结构。组合能让客户以一致的方式处理个别对象以及对象组合。

举个例子
类图
image.png
伪代码

定义个别对象与组合对象的超类,在Client处使用该类,不需要区分个别还是组合对象

public abstract class Component{
  public void add(Component c){
    throw new UnsupportedOperationException();
  }
  public void remove(Component c){
    throw new UnsupportedOperationException();
  }
  public Component getChild(int i){
    throw new UnsupportedOperationException();
  }
  public String getName(){
    throw new UnsupportedOperationException();
  }
  public String getChildSize(){
    throw new UnsupportedOperationException();
  }
  public void download(){
    throw new UnsupportedOperationException();
  }
}

定义个别对象

public class File extends Component{
  String name;
  public File(String name){
    this.name = name;
  }
  public String getName(){j// 关注点在getName和download自身,其他方法如add remove等使用默认父类实现。
    return this.name;
  }
  public void download(){
    System.out.println('download"+getName());
  }
}

定义组合对象

public class Folder extends Component{
  String name;
  List<Component> list; // 关注点在对于list的增删遍历
  public Folder(String name){
    this.name = name;
    list = new ArrayList();
  }
  public void add(Component c){
    list.add(c);
  }
  public void remove(Component c){
    list.remove(c);
  }
  public Component getChild(int i){
    list.get(i);
  }
  public String getName(){
    name;
  }
  public String getChildSize(){
    reture list.size();
  }
  public void download(){// 目录的下载
    Iterator iterator = list.iterator();
     while(iterator.hasNext()){
      Component c = iterator.next();
      c.download();// 子的下载,既可以是文件,也可以是子目录
    }
  }
}

Client

public class Client{
  Component c;
  public Client(Component c){
    this.c = c;
  }
  public void download(){
    c.download();
  }
}

示例

Component folder1 = new Folder("folder1");
Component folder2 = new Folder("folder2");
Component folder3 = new Folder("folder3");
folder1.add(new File("file1"));
folder1.add(new File("file2"));
folder2.add(new File("file3"));
folder2.add(new File("file4"));
folder3.add(folder1);
folder3.add(folder2);
Client client = new Client(folder3);
client.download();
总结

个别对象继承Component,对象组合继承Compoent但又是Component的集合,个别对象与对象组合都继承Compoent因此有相同的操作download,区别是个别对象的download操作的是自身,而对象组合的download操作的是Component的集合。

上一篇下一篇

猜你喜欢

热点阅读