Saturday, September 20, 2014

Composite Design Pattern

Definition

Composite design pattern is a Structural Design Pattern that provide 0 to many parent child relationship. Simply, an Object composes of similar types of objects and this second level objects could comprise similar type of objects  which structure part-whole relationship.

Intention
  • Composes objects into tree structures to represent part-whole hierarchies.
  • Lets clients treat individual objects and compositions of objects uniformly.
Components

Composite - Acts like a container that holds similar type of objects.
Leaf - Node in the hierarchy.
Component - The common interface that needs to be implemented by Composite and Leaf.
Client - Uses the Composite to traverse through the Leaves.



 Component

 public interface Shape {

    public void draw();
}

Leaf 1

public class Oval implements Shape {

    @Override
    public void draw() {
        System.out.println("This is an Oval");
    }

}

Leaf 2

public class Circle implements Shape {

    @Override
    public void draw() {
        System.out.println("This is a Circle");

    }

}

Composite

public class ShapeComposite implements Shape {

    private ArrayList<Shape> shapeList = new ArrayList<Shape>();

    @Override
    public void draw() {
        for (Shape shapeType : shapeList) {
            shapeType.draw();

        }
    }

    public void addShape(Shape shape) {
        shapeList.add(shape);
    }

    public void removeShape(Shape shape) {
        shapeList.remove(shape);
    }

    public void clearAll() {
        shapeList.clear();
    }

}


public class Client {

    public static void main(String[] args) {

        Shape circl1 = new Circle();
        Shape oval1 = new Oval();
        ShapeComposite shapeComposite = new ShapeComposite();
        ShapeComposite shapeComposite2 = new ShapeComposite();

        shapeComposite.addShape(circl1);
        shapeComposite.addShape(oval1);
        shapeComposite2.addShape(shapeComposite);
        shapeComposite2.draw(); // Output: This is a Circle
                                // This is an Oval

    }

}

No comments: