ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Object and Class Adapters | 181

The client classMaincreates an instance of the adapter class and calls the method


request( )defined in theITargetinterface. The client sees only the interface that’s


implemented by the adapter. Object adapters are like traffic cops, as they intercept


method calls and decide what to do with them. Some of the method calls are directed


to the appropriate methods in theAdapteeclass. TheAdaptorclass keeps tight control


of access to the existing class by implementing only theITargetinterface. The client


doesn’t even know that the adapter’s using an existing class. TheAdapteeclass could


have many public methods and properties that aren’t accessible through the adapter.


Because the Adaptorclass creates an instance of theAdaptee class, there’stight


couplingbetween them. This doesn’t allow the adapter to use a subclass ofAdaptee


or use a totally different existing class without modifying existingAdapter code.


Using a parameterized adapter class


A variation on the previous example of the adapter is to require the client to pass an


instance of the existing class when creating an adapter. You can do this by using a


parameterized constructor in the adapter class. The following changes are needed in


theAdapter class constructor.


public function Adapter(a:Adaptee)
{
this.adaptee = a;
}

This is desirable in many cases, as it reduces the coupling between theAdapterand


Adapteeclasses, providing more flexibility. However, this puts the burden on the cli-


ent to create an instance ofAdaptee class and pass it to the adapter.


var adaptee:Adaptee = new Adaptee( );
var target:ITarget = new Adapter(adaptee);

The disadvantage of doing it this way is that the existing class is no longer hidden


from the client. The client creates the instance ofAdapteethat is passed to the


Adaptor. This could potentially cause disruption if the client inadvertently manipu-


lates theAdaptee instance.


Class Adapters


When the adapter usesinheritanceto access an existing class, it’s known as aclass


adapter. The adapter class extends the existing class and has anis-arelationship with


public function Main( )
{
var target:ITarget = new Adapter( );
target.request( );
}
}
}


Example 5-4. Main.as (continued)

Free download pdf