In
software engineering
Software engineering is a systematic engineering approach to software development.
A software engineer is a person who applies the principles of software engineering to design, develop, maintain, test, and evaluate computer software. The term '' ...
, the composite pattern is a partitioning
design pattern
A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The "Gang of Four" boo ...
. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.
Overview
The Composite
design pattern is one of the twenty-three well-known
''
GoF design patterns''
that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
What problems can the Composite design pattern solve?
* A part-whole hierarchy should be represented so that clients can treat part and whole objects uniformly.
* A part-whole hierarchy should be represented as tree structure.
When defining (1)
Part
objects and (2)
Whole
objects that act as containers for
Part
objects, clients must treat them separately, which complicates client code.
What solution does the Composite design pattern describe?
* Define a unified
Component
interface for both part (
Leaf
) objects and whole (
Composite
) objects.
* Individual
Leaf
objects implement the
Component
interface directly, and
Composite
objects forward requests to their child components.
This enables clients to work through the
Component
interface to treat
Leaf
and
Composite
objects uniformly:
Leaf
objects perform a request directly,
and
Composite
objects
forward the request to their child components recursively downwards the tree structure.
This makes client classes easier to implement, change, test, and reuse.
See also the UML class and object diagram below.
Motivation
When dealing with Tree-structured data, programmers often have to discriminate between a leaf-node and a branch. This makes code more complex, and therefore, more error prone. The solution is an interface that allows treating complex and primitive objects uniformly. In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and Computer program, code. The data is in the form of Field (computer science), fields (often kno ...
, a composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality. This is known as a "
has-a
In database design, object-oriented programming and design (see object oriented program architecture), has-a (has_a or has a) is a composition relationship where one object (often called the constituted object, or part/constituent/member object) ...
" relationship between objects. The key concept is that you can manipulate a single instance of the object just as you would manipulate a group of them. The operations you can perform on all the composite objects often have a
least common denominator
In mathematics, the lowest common denominator or least common denominator (abbreviated LCD) is the lowest common multiple of the denominators of a set of fractions. It simplifies adding, subtracting, and comparing fractions.
Description
The lo ...
relationship. For example, if defining a system to portray grouped shapes on a screen, it would be useful to define resizing a group of shapes to have the same effect (in some sense) as resizing a single shape.
When to use
Composite should be used when clients ignore the difference between compositions of objects and individual objects.
If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice; it is less complex in this situation to treat primitives and composites as homogeneous.
Structure
UML class and object diagram
In the above
UML class diagram
In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the rel ...
, the
Client
class doesn't refer to the
Leaf
and
Composite
classes directly (separately).
Instead, the
Client
refers to the common
Component
interface and can treat
Leaf
and
Composite
uniformly.
The
Leaf
class has no children and implements the
Component
interface directly.
The
Composite
class maintains a container of child
Component
objects (
children
) and forwards requests
to these
children
(
for each child in children: child.operation()
).
The object collaboration diagram
shows the run-time interactions: In this example, the
Client
object sends a request to the top-level
Composite
object (of type
Component
) in the tree structure.
The request is forwarded to (performed on) all child
Component
objects
(
Leaf
and
Composite
objects) downwards the tree structure.
;Defining Child-Related Operations
There are two design variants for defining and implementing child-related operations
like adding/removing a child component to/from the container (
add(child)/remove(child)
) and accessing a child component (
getChild()
):
* ''Design for uniformity:'' Child-related operations are defined in the
Component
interface. This enables clients to treat
Leaf
and
Composite
objects uniformly. But
type safety
In computer science, type safety and type soundness are the extent to which a programming language discourages or prevents type errors. Type safety is sometimes alternatively considered to be a property of facilities of a computer language; that ...
is lost because clients can perform child-related operations on
Leaf
objects.
* ''Design for type safety:'' Child-related operations are defined only in the
Composite
class. Clients must treat
Leaf
and
Composite
objects differently. But type safety is gained because clients ''cannot'' perform child-related operations on
Leaf
objects.
The Composite design pattern emphasizes ''uniformity'' over ''type safety''.
UML class diagram
;Component
* is the abstraction for all components, including composite ones
* declares the interface for objects in the composition
* (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate
;Leaf
* represents leaf objects in the composition
* implements all Component methods
;Composite
* represents a composite Component (component having children)
* implements methods to manipulate children
* implements all Component methods, generally by delegating them to its children
Variation
As it is described in
Design Patterns
''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a foreword ...
, the pattern also involves including the child-manipulation methods in the main Component interface, not just the Composite subclass. More recent descriptions sometimes omit these methods.
Example
The following example, written in
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
, implements a graphic class, which can be either an ellipse or a composition of several graphics. Every graphic can be printed. In
Backus-Naur form,
Graphic ::= ellipse , GraphicList
GraphicList ::= empty , Graphic GraphicList
It could be extended to implement several other shapes (rectangle, etc.) and methods (
translate
Translation is the communication of the meaning of a source-language text by means of an equivalent target-language text. The English language draws a terminological distinction (which does not exist in every language) between ''transla ...
, etc.).
Java
import java.util.List;
import java.util.ArrayList;
/** "Component" */
interface Graphic
/** "Composite" */
class CompositeGraphic implements Graphic
/** "Leaf" */
class Ellipse implements Graphic
/** Client */
class CompositeDemo
See also
*
Perl Design Patterns Book ''Perl Design Patterns Book'' is an online textbook about Perl style and design and analysis. The contents are licensed under GNU Free Documentation License.
External links
* Perl Design Patterns (wiki)
Perl Design Patterns Bookin Savannah
A ...
*
Mixin
*
Law of Demeter
References
External links
Composite Patternimplementation in Java
*
Composite pattern description from the Portland Pattern RepositoryComposite pattern in UML and in LePUS3, a formal modelling languageClass::Delegation on CPAN"The End of Inheritance: Automatic Run-time Interface Building for Aggregated Objects"by
Paul BaranowskiPerfectJPattern Open Source Project Provides componentized implementation of the Composite Pattern in Java
A persistent Java-based implementation
Composite Design Pattern
{{DEFAULTSORT:Composite Pattern
Software design patterns
Articles with example Java code
Articles with example C Sharp code