组合模式(Composite)

王朝other·作者佚名  2006-02-01
窄屏简体版  字體: |||超大  

将对象建立为部分-整体的层次关系或者构造树的数据表现。

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);

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航