Upload
hollye
View
29
Download
0
Embed Size (px)
DESCRIPTION
BTS530: Major Project Planning and Design. The Composite Pattern All References and Material From: Design Patterns,by (GOF!) E.Gamma, R.Helm, R.Johnson, J.Vlissides, Addison-Wesley, 2001. Composite. The Problem: - PowerPoint PPT Presentation
Citation preview
The Composite PatternAll References and Material From: Design Patterns,by (GOF!) E.Gamma, R.Helm, R.Johnson, J.Vlissides, Addison-Wesley, 2001
BTS530: Major Project Planning and Design
CompositeThe Problem:How do you treat a group or composition
structure of objects the same way (polymorphically) as a non-composite object?
Composite
A Suggestion/Solution:Define classes for composite and
atomic object so that they implement the same interface.
CompositeClassic example: Graphics applications
users can group components into larger components which can be grouped to form larger components…and so on.
problem: the code must treat primitive and container objects differently even though the user might treat them the same
Composite pattern uses recursive composition so clients don’t have to make a distinction
Design Patterns, p.163
Graphic
draw()add(Graphic g)
remove(Graphic)getChild(int)
Line
draw()
Picture
draw()add(Graphic g)remove(Graphic)getChild(int)
Rectangle
draw()
Text
draw()
1…n
forall g in graphics g.draw()
add g to list of graphics
graphics
Design Patterns, p.163
aPicture
aPicture aLine aRectangle
aText aLine aRectangle
Design Patterns, p.164
Component
operation()add(Component)
remove(Component)getChild(int)
Composite
operation()add(Component)remove(Component)getChild(int)
Leaf
operation()
1…n
forall c in children c.operation()
Client
children
Design Patterns, p.164
aComposite
aComposite aLeaf aLeaf
aLeaf aLeaf aLeaf
Design Patterns, p.165
CompositeComponent (Graphic):
declares the interface for objects in the compositionimplements common default behaviourdeclares an interface for managing child components
Leaf (Rectangle, Line, Text)has no childrendefines behaviour for primitives
Composite (Picture)defines behaviour for components having childrenstores child componentsimplements child-related operations through the
component interface
Design Patterns, p.165
CompositeThe Client:
uses the Component class interface to interact with objects in the composite structure
If recipient is Leafrequest handled directly
If recipient is Compositerequest is usually forwarded to child components,
possibly performing additional operations before and/or after forwarding
Design Patterns, p.165
Composite Exercise
draw a sequence diagram to illustrate: draw line l draw circle c group l and c into graphicA draw box b1 draw box b2 group b1 and b2 into graphicB group graphicB into graphicA select c in graphicA(assume lines, circles, boxes exist but not graphics)
: DrawingHandler
l : Line c : Circle A : Graphic b1 : Box B : Graphicb2 : Box
draw()
draw()
create()
add(l)
add(c)
draw()
draw()
create()
add(b1)
add(b2)
add(B)
getChild(c)