当前位置:编程学习 > JAVA >>

设计模式--结构模式--组合模式--Java

Composite
 
 
intent
Composeobjects into tree structures to represent part-whole hierarchies. Compositelets clients treat individual objects and compositions of objects uniformly
将对象组合成树形结构以表示“部分-整体”的层次结构。C o m p o s i t e使得用户对单个对象和组合对象的使用具有一致性
 
applicability
you want to represent part-whole hierarchies of objects
you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly
你想表示对象的部分-整体层次结构
你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象
UML
 
 
participants
Component(Graphic)
declares the interface for objectsin the composition.
implements default behavior for theinterface common to all classes, as appropriate.
declares an interface for accessingand managing its child components.
(optional) defines an interface foraccessing a component's parent in the recursive structure, and implements it ifthat's appropriate.
Leaf(Rectangle, Line, Text, etc.)
represents leaf objects in thecomposition. A leaf has no children.
defines behavior for primitiveobjects in the composition.
Composite(Picture)
defines behavior for componentshaving children.
stores child components.
implements child-related operationsin the Component interface.
Client
manipulates objects in thecomposition through the Component interface.
 
组合模式分为安全式与透明式
安全式
下面的绘图例子中,Line、Circle、Rectangle属于Leaf,而只有Picture才具有add、remove、getChild方法。所以说对于Client端调用来讲是安全的,不会滥用,但是Client必须搞清楚哪些是Leaf哪些是Composite
透明式
下面的绘图例子中,对于leaf也具有add、remove、getChild方法,所以对于客户端来讲可以忽略哪些是leaf节点,哪些是Composite,但是在运行时如果错误使用会抛出运行时异常,譬如在leaf节点上添加节点。
在实现时,我们可以在leaf节点的add、remove、getChild方法中抛出运行时异常来避免Client端错误调用。
这两种实现方式,需要根据需求来权衡选择。
SWing---Composite Patterns
 
 
感兴趣的可以查阅jdk文档,分辨其是透明式的实现方式还是安全式的实现方
补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,