将对象建立为部分-整体的层次关系或者构造树的数据表现。
<shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"></shapetype><stroke joinstyle="miter"></stroke><formulas></formulas><f eqn="if lineDrawn pixelLineWidth 0"></f><f eqn="sum @0 1 0"></f><f eqn="sum 0 0 @1"></f><f eqn="prod @2 1 2"></f><f eqn="prod @3 21600 pixelWidth"></f><f eqn="prod @3 21600 pixelHeight"></f><f eqn="sum @0 0 1"></f><f eqn="prod @6 1 2"></f><f eqn="prod @7 21600 pixelWidth"></f><f eqn="sum @8 21600 0"></f><f eqn="prod @7 21600 pixelHeight"></f><f eqn="sum @10 21600 0"></f><lock v:ext="edit" aspectratio="t"></lock><shape id="_x0000_i1025" style="WIDTH: 6in; HEIGHT: 199.5pt" type="#_x0000_t75"></shape><imagedata src="file:///C:%5CDOCUME~1%5CADMINI~1%5CLOCALS~1%5CTemp%5Cmsohtml1%5C01%5Cclip_image001.png" o:title=""></imagedata>
Component (DrawingElement)
声明组合对象接口
显现接口默认操作。
声明访问并管理子组件的接口
(可选)定义访问父组件接口。
Leaf(PrimitiveElement)
表示叶子对象,叶子没有孩子。
实现叶子对象操作。
Composite(CompositeElement)
定义有孩子组件的行为
保存孩子组件
实现孩子组件相关操作。
Client(CompositeApp)
通过组件接口操作组合模式的对象。
代码:
//Component
public abstract class DrawingElement{
protected String name;
public DrawingElement(String name){
this.name=name;
}
public abstract void Add(DrawingElement d);
public abstract void Remove(DrawingElement d);
public abstract void Display(int indent);
}
//Leaf
public class PrimitiveElement extends DrawingElement{
public PrimitiveElement(String name){
super(name)
}
public void Add(DrawingElement c){
System.out.println(“Cannot add”);
}
public void Remove(DrawingElement c){
System.out.println(“Cannot remove”);
}
public void Display(int indent){
System.out.println(“draw a indent”+name);
}
}
//Composite
import java.util.ArrayList;
public class CompositeElement extends DrawingElement{
private ArrayList elements =new ArrayList();
public CompositeElement(String name){
super(name);
}
public void Add(DrawingElement d){
elements.add(d);
}
public void Remove(DrawingElement d){
elements.Remove(d);
}
public void Display(int indent){
System.out.println(“draw a indent”+name);
for(int i=0; i<elements.size();i++){
(DrawingElement)(elements.get(i)).Display(indent+2);
}
}
public class CompositeApp{
public static void main(String[] args){
CompositeElement root=new CompositeElement(“picture”);
root.Add(new PrimitiveElement(“red line”));
root.Add(new PrimitiveElement(“blue line”));
root.Add(new PrimitiveElement(“green line”));
CompositeElement comp=new CompositeElement(“tow ciricles”);
comp.Add(new PrimitiveElement(“black circle”);
comp.Add(new PrimitiveElement(“white circle”);
root.Add(comp);
PrimitiveElement 1=new PrimitiveElement(“yello line”);
root.Add(l);
root.Remove(l);
root.Display(l);
}
}