Instructor: Stefan Mitsch
Inheritance
Composition
Composite represents part-whole hierarchies in a tree structure
Problem illustration: want to pack products into boxes; a box can contain several products and smaller boxes
How to represent a tree structure?
Problem
Intent
Structure
Example Object Diagram
The Component interface describes operations that are common to both simple and complex elements of a tree
Component
The Leaf is a basic element of a tree that does not have sub-elements; usually, leaf components do the bulk of the real work
Leaf
The Composite (a.k.a. Container) has sub-elements and delegates work
Composite
Container
The Client works uniformly with all elements through the Component interface
Client
List
Array
// component public interface Shape { int getX(); int getY(); void paint(java.awt.Graphics graphics); } // leafs public class Dot implements Shape { /*...*/ } public class Circle implements Shape { /*...*/ } // composite public class Figure implements Shape { private List<Shape> children = new ArrayList<>(); public Figure(Shape... components) { children.addAll(components); } public void add(Shape c) { children.add(c); } public void remove(Shape c) { children.remove(c); } public void paint(java.awt.Graphics graphics) { for (Shape c : children) c.paint(graphics); } }
add
remove
Code Smell: A class processes single and multiple objects using separate pieces of code
Before: Client needs to distinguish multiple methods
List<Spec>
Code Smell: Subclasses in a hierarchy implement the same composite
Before: Duplicate composite code