[color=red]COMPOSITE[/color] (Object Structural)
[color=red]Purpose[/color]
Facilitates the creation of object hierarchies where each object
can be treated independently or as a set of nested objects
through the same interface.
[color=red]Use When[/color]
1 Hierarchical representations of objects are needed..
2 Objects and compositions of objects should be treated uniformly.
[color=red]Example[/color]
Sometimes the information displayed in a shopping cart is the
product of a single item while other times it is an aggregation
of multiple items. By implementing items as composites we can
treat the aggregates and the items in the same way, allowing us
to simply iterate over the tree and invoke functionality on each
item. By calling the getCost() method on any given node we
would get the cost of that item plus the cost of all child items,
allowing items to be uniformly treated whether they were single
items or groups of items.
[color=red]Purpose[/color]
Facilitates the creation of object hierarchies where each object
can be treated independently or as a set of nested objects
through the same interface.
[color=red]Use When[/color]
1 Hierarchical representations of objects are needed..
2 Objects and compositions of objects should be treated uniformly.
[color=red]Example[/color]
Sometimes the information displayed in a shopping cart is the
product of a single item while other times it is an aggregation
of multiple items. By implementing items as composites we can
treat the aggregates and the items in the same way, allowing us
to simply iterate over the tree and invoke functionality on each
item. By calling the getCost() method on any given node we
would get the cost of that item plus the cost of all child items,
allowing items to be uniformly treated whether they were single
items or groups of items.
package javaPattern.composite;
import java.util.ArrayList;
interface Component{
public void operation();
}
public class Composite implements Component{
private ArrayList<Component> al = new ArrayList<Component>();
@Override
public void operation() {
System.out.println("Composite's operation...");
}
public void add(Component c){
al.add(c);
}
public void remove(Component c){
al.remove(c);
}
public Component getChild(int index){
return al.get(index);
}
}
class Leaf implements Component{
@Override
public void operation() {
System.out.println("leaf's operation..");
}
}
class Client{
public static void main(String[] args) {
Composite composite = new Composite();
Component component1 = new Leaf();
Component component2 = new Leaf();
composite.add(component1);
composite.add(component2);
}
}
本文详细介绍了组合模式的概念及其在创建对象层次结构中的应用。通过统一的接口处理单个对象及对象集合,实现对象与对象组合的一致性操作。以购物车为例,展示了如何使用组合模式来简化成本计算。
2099

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



