ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Example: Music Playlists | 217

Key OOP Concepts in the Composite Pattern


The key OOP concept embedded in the composite pattern ispolymorphism. Poly-


morphism can be broadly defined as the ability of objects instantiated from different


classes to respond to the same method calls in specific ways. This is possible because


the method signature’s the same, even though the objects are instantiated from dif-


ferent classes. In short, the methods in the different classes show a common inter-


face to clients.


Since the composite pattern allows clients to treat both leaf and composite nodes the


same way through a common interface, it’s a good example of polymorphism. This is


due to both leaf and composite classes implementing the same component interface


by subclassing the abstract component class.


Implementations of operations truly exemplify polymorphism. In the minimalist


examples, theoperation( )method was implemented one way in the leaf nodes and


another way in the composite nodes. The composite nodes have to forward the


operation( )call to all its child nodes. Theoperation( )responds differently in both


leaf and composite nodes, but the client doesn’t need to know or care about these


differences. The client doesn’t see the different implementations; it sees only the


interface.


Example: Music Playlists


Have you created music playlists in your favorite digital music jukebox? If so, have


you taken the next step and embedded playlists inside other playlists to create ever


larger playlists? This is a perfect application to implement a composite pattern. A


library of digital music contains songs and playlists. A song is a primitive object,


Figure 6-5. Deleting components from the tree structure


root

Composite 1
Composite 2

leaf 6

leaf 2

leaf 3 leaf 4 leaf 5

leaf 2

root

Composite 1

Composite 2

leaf 6

leaf 2

leaf 4 leaf 5

leaf 2

root

Composite 1 leaf 6

leaf 2 leaf 2

Display tree First child of second
child of ‘root’ removed

Second child of
‘root’ removed

Second child
of root

First child of second
child of root

Second child
of root
Free download pdf