ActionScript 3.0 Design Patterns

(Chris Devlin) #1

178 | Chapter 5: Adapter Pattern


fit an adult’s bottom, and we now need to convert that interface to fit a toddler’s


smaller bottom. We need an adapter that presents the correct interface to fit the cur-


rent context. The toilet seat adapter was built to do precisely that. We get to use an


existing object whose interface has been converted to one that the client expects.


How is this analogous to an adapter pattern? We have an existing object (toilet seat);


a new interface it needs to conform to (a toddler’s bottom); an adapter that converts


the interface (toilet seat adapter); and a new client (toddler).


Let’s extend this analogy to computer code. The existing object would be analogous


to an existing class that creates objects. The new interface would represent new


requirements for this class. The adapter would be another class that implements the


new interface by using the existing class.


What would be the alternative to using an adapter in this case? We could rewrite or


modify the code in the existing class to fit the new interface. This is analogous to


buying one of those small potties built for toddlers (with no plumbing). I think most


people would rather not have to deal with the additional cost and the disposal issue.


This can be as painful as changing existing code that already works, introducing


bugs, and breaking dependencies. An adapter would be a better option in both cases.


Key Features of the Adapter Pattern


Before considering an adapter pattern for a project, a couple conditions should exist:



  • An existing class that meets some of the implementation requirements, but
    whose interface is incompatible in the new context of use

  • A target interface for the new context


If these conditions exist, then we can develop an adapter class that uses the existing


class to implement the targetinterface. The new context should be thoroughly ana-


lyzed, and the new requirements defined, before thinking about implementation. In


other words, we should know the desired interface before we look at existing classes


Figure 5-1. Toilet seat adapter


Existing object

Toilet

Adapter

Toilet seat
adapter

New context

Client
Free download pdf