120 likes | 249 Views
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:
E N D
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: • 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.
Composite • Classic 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
1…n graphics add g to list of graphics forall g in graphics g.draw() Design Patterns, p.163
aPicture aPicture aLine aRectangle aText aLine aRectangle Design Patterns, p.164
Client 1…n children forall c in children c.operation() Design Patterns, p.164
aComposite aComposite aLeaf aLeaf aLeaf aLeaf aLeaf Design Patterns, p.165
Composite Component (Graphic): • declares the interface for objects in the composition • implements common default behaviour • declares an interface for managing child components Leaf (Rectangle, Line, Text) • has no children • defines behaviour for primitives Composite (Picture) • defines behaviour for components having children • stores child components • implements child-related operations through the component interface Design Patterns, p.165
Composite The Client: • uses the Component class interface to interact with objects in the composite structure • If recipient is Leaf • request handled directly • If recipient is Composite • request 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)