Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

5.

Composite

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 1


Intent
• Composite is a structural design pattern that lets
you compose objects into tree structures and
then work with these structures as if they were
individual objects

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 2


Real-World Analogy
Military Structure

• Armies of most countries are structured as hierarchies.


• Orders are given at the top of the hierarchy and passed down
onto each level until every soldier knows what needs to be done.
Dr Vengadeswaran, Asst. Prof IOE 321 SDP 3
General Structure
1. Base Component - Base component is
the interface for all objects in the
composition, client program uses base
component to work with the objects in
the composition. It can be an interface or
an abstract class with some methods
common to all the objects.
2. Leaf - Defines the behaviour for the
elements in the composition. It
implements base component. – Business
logic

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 4


General Structure
3. Composite - It consists of leaf
elements as a hierarchy and implements
the operations in base component

4. Client works with all elements


through the component interface. As
a result, the client can work in the
same way with both simple or
complex elements of the tree.

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 5


Problem
• Need to create a structure in a way that the objects in the structure must
be treated the same way
• Drawing is a structure consist of Objects (Circles, Lines, Triangles etc..)

• When we fill the drawing with color (Say red) à Same color also
get applied to the object in the drawing
• Drawing made up of different parts à all have same operations

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 6


General Structure

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 7


Implementation

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 8


Implementation

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 9


Client code
Main function()

Output

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 10


Applicability
• Use the Composite pattern when you have to
implement a tree-like object structure.
• Use the pattern when you want the client code to
treat both simple and complex elements uniformly.

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 11


Pros and Cons
Pros:
• Work with complex tree structures more conveniently:
• Open/Closed Principle: Introduce new element types
into the app without breaking the existing code, which
now works with the object tree.
Cons:
• It might be difficult to provide a common interface for
classes whose functionality differs too much.

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 12


Thank You

Dr Vengadeswaran, Asst. Prof IOE 321 SDP 13

You might also like