合成模式(整体-部分模式)

八. 合成模式(整体-部分模式)
整理自 《java与模式》阎宏编著


1.意图:

合成模式将“部分”与”整体”的关系用树结构表示出来。合成模允许客户端把一个个单独的成份对象和由它们复合而成的合成对象同等看待。

2.类图:
[img]http://eneasy.iteye.com/upload/picture/pic/10075/386fcd2d-d47f-3a63-ad76-5671ab4dd2f0.jpg[/img]


3.原理:

合成模式用来设计一个公共的接口,即可以提供给单独的成份对象使用,也可以提供给合成的对象使用,这样客户端就可以以一种统一的接口来使用单独的成份对象和合成对象。

4.特征:

抽象构件(Component):抽象角色,给出共有的接口和默认的行为。

树叶构件(Leaf):没有子对象,定义出参加组合的原始对象的行为。

树枝构件(Composite):有子对象,给出树枝构件对象的行为。
5.说明:

合成模式必须提供管理子对象的行为,如:addChild(),

removeChild(),getChildren()等。

6.使用案例:
文件系统(文件夹为合成对象,文件为成份对象)

7.代码:

//Composite.java

public abstract class Component

{

/**

* Add child to Composite

*/

public void addChild(Component child)

{

// default implementation - throw error

throw new RuntimeException("addChild(): Not intended to be called");

}



/**

* Remove child from Composite

*/

public void removeChild(Component child)

{

// default implementation - throw error

throw new RuntimeException("remove(): Not intended to be called");

}



/**

* @return iterator over children of this component, or <code>null</code>

* if there are no children.

*/

public Iterator getChildren()

{

return null;

}



/**

* Sample method

*/

public abstract void sampleOperation();

}





// Composite.java

public class Composite extends Component

{

/**

* Stores components of this composite

*

*/

private ArrayList components;



public void addChild(Component child)

{

if (components == null)

{

components = new ArrayList();

}

components.add(child);

}



public void removeChild(Component child)

{

if (components != null)

{

components.remove(child);

}

}



public Iterator getChildren()

{

if (components == null)

{

return null;

}

return components.iterator();

}



public void sampleOperation()

{

if (components != null)

{

Iterator it = components.iterator();

while (it.hasNext())

{

((Component) it.next()).sampleOperation();

}

}

}

}



// Leaf.java

public class Leaf extends Component

{

public void sampleOperation()

{

// implement this operation

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值