Blog by Leven

Composite-Pattern

what is composite pattern

In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that is 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.

the usage of composite pattern

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.

It can be used in partial/whole scene, such as tree menus, files/folder, tree-structured hierarchies.

the UML class object diagram for the Composite design pattern is shown below,

the UML class object diagram for the Composite design pattern

scene and example

Here is an example written in python, and it use child graphics to composite a multiple graphic through uniform Component(Graphic).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
Composite pattern example.
"""
from abc import ABC, abstractmethod

NOT_IMPLEMENTED = "You should implement this."


# Component
class Graphic(ABC):
@abstractmethod
def print(self):
raise NotImplementedError(NOT_IMPLEMENTED)

# "Composite"
class CompositeGraphic(Graphic):
def __init__(self):
self.graphics = []

def print(self):
for graphic in self.graphics:
graphic.print()

def add(self, graphic):
self.graphics.append(graphic)

def remove(self, graphic):
self.graphics.remove(graphic)

# "Leaf"
class Ellipse(Graphic):
def __init__(self, name):
self.name = name

def print(self):
print("Ellipse:", self.name)


# "Client"
ellipse1 = Ellipse("1")
ellipse2 = Ellipse("2")
ellipse3 = Ellipse("3")
ellipse4 = Ellipse("4")

graphic = CompositeGraphic()
graphic1 = CompositeGraphic()
graphic2 = CompositeGraphic()

graphic1.add(ellipse1)
graphic1.add(ellipse2)
graphic1.add(ellipse3)
graphic1.remove(ellipse2)

graphic2.add(ellipse4)

graphic.add(graphic1)
graphic.add(graphic2)

graphic.print()

Reference document

wiki - Composite_pattern