COMPOSITE (Object Structural)
Purpose
Facilitates the creation of object hierarchies where each object
can be treated independently or as a set of nested objects
through the same interface.
Use When
1 Hierarchical representations of objects are needed..
2 Objects and compositions of objects should be treated uniformly.
Example
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);
- }
- }