Composite Pattern
Composite pattern describes as group of objects that will be treated in same manner as single instance of object. Main logic behind a composite pattern is “composing” the objects in tree structures and represent it in part or whole hierarchies. Full implementation of composite pattern give clients treats individual objects and it compositions equivalently.
Questions: When to use composite pattern:
This pattern could be use whenever clients want to disregard difference between individual and compositions of the objects. Let’s take example when you are doing coding and find that you are using many objects in same way and those have nearly matching code which handles each of them then it would be good choice to use composite design pattern. It would be less complex for this situation to treat primitives and composites as identical.
Example:
See example below example where it implements graphic class which could be either ellipse or composition of several graphics. Here every graphic could be printed.
- Create Component Interface:
public interface Graphic { public void print(); }
- Composite class:
import java.util.ArrayList; import java.util.List; public class CompositeGraphic implements Graphic { // Collection child graphics. private List<Graphic> childGraphics = new ArrayList<Graphic>(); public void print() { for (Graphic graphic : childGraphics) { graphic.print(); } } // Adds the graphic to the composition. public void add(Graphic graphic) { childGraphics.add(graphic); } // Removes the graphic from the composition. public void remove(Graphic graphic) { childGraphics.remove(graphic); } }
- Create Leaf:
public class Ellipse implements Graphic{ public void print() { System.out.println("Ellipse"); } }
- Client Class:
public class CompositeClient { public static void main(String[] args) { // Initialize four ellipses Ellipse ellipse1 = new Ellipse(); Ellipse ellipse2 = new Ellipse(); Ellipse ellipse3 = new Ellipse(); Ellipse ellipse4 = new Ellipse(); // Initialize three composite graphics CompositeGraphic graphic = new CompositeGraphic(); CompositeGraphic graphic1 = new CompositeGraphic(); CompositeGraphic graphic2 = new CompositeGraphic(); // Composes graphics graphic1.add(ellipse1); graphic1.add(ellipse2); graphic1.add(ellipse3); graphic2.add(ellipse4); graphic.add(graphic1); graphic.add(graphic2); graphic.print(); } }
- That’s it. Below is list of all design patterns link:
Creational Patterns:
Structural Patterns:
Behavioral Patterns:
- Chain of Responsibility
- Command
- Interpreter
- Iterator
- Mediator
- Memento
- Observer
- State
- Strategy
- Template Method
- Visitor