组合模式定义:将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
组合模式初步理解:将对象分为部分和整体,整体;部分和整体又属于一个大的整体,整体中又有部分和整体。整体和部分有一些公共的属性,因此有必要抽象出一个类,使整体和部分继承这个类。
code…
抽象的父类,为整体和部分提供属性和方法:
public abstract class Component {
private String name;
public Component(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void show();
}
部分类:
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override public void show() {
System.out.println(this.getName());
}
}
整体类:
public class Composite extends Component{
private ArrayList<Component> arrayList=new ArrayList<>();
public Composite(String name) {
super(name);
}
public ArrayList<Component> getArrayList() {
return arrayList;
}
public void setArrayList(ArrayList<Component> arrayList) {
this.arrayList = arrayList;
}
public void add(Component component)
{
arrayList.add(component);
}
@Override public void show() {
Iterator it=arrayList.iterator();
System.out.println(this.getName());
while(it.hasNext())
{
Component component=(Component) it.next();
System.out.print(" ");
component.show();
}
}
}
main方法:
public class Main {
public static void main(String[] args) {
Composite root=new Composite("root");
Leaf leaf1=new Leaf("leaf1");
Leaf leaf2=new Leaf("leaf2");
Leaf leaf3=new Leaf("leaf3");
root.add(leaf1);
root.add(leaf2);
root.add(leaf3);
Composite compositeX=new Composite("compositeX");
Leaf leafX1=new Leaf("leafX1");
Leaf leafX2=new Leaf("leafX2");
compositeX.add(leafX1);
compositeX.add(leafX2);
root.add(compositeX);
Composite.out(root);
}
}
组合模式的应用:文件管理。在管理文件时,有文件夹和文件,文件夹中又有文件和文件夹。文件夹就相当于整体类,文件就相当于部分类。不管时文件还是文件夹都有名字,因此抽象出一个父类。文件夹中存放的是这个父类类型。就像ArrayList中存放的是Component一样。在遍历时,遇到部分类就调用其方法输出部分类的名字;遇到整体类,就调用整体类的遍历方法。
| 上一篇 |
---The End---
| 下一篇 |
本文深入探讨了组合模式的概念,通过将对象组织成树形结构来表示‘部分-整体’的层次结构,实现对单个对象和组合对象一致性的操作。以文件管理和代码示例详细讲解了如何应用组合模式。
196

被折叠的 条评论
为什么被折叠?



