ActionScript 3.0 Design Patterns

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

and their functionality to figure out if they’ll fit the bill. We can then develop an


adapter class that implements the target interface. There’s no point to adapting an


existing class if it doesn’t provide some benefit, such as savings in development time


compared to developing a whole new class.


Object and Class Adapters


An adapter can exploit an existing class to implement functionality in two ways. The


adapter can use eithercompositionorinheritanceto access an existing class. If the


adapter subclasses the existing class, it will inherit the methods and properties. If the


adapter uses composition to access the existing class, the adapter class will hold a


reference to an instance of the existing class, and use its methods and properties for


implementation. In OOP, composition is generally preferred over inheritance. How-


ever, as we will see in subsequent examples, there are good arguments for both


approaches depending on the context. Either way, the idea is to use the properties


and methods of the existing class to provide most or some of the functionality


required.


Object Adapters


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


object adapter. Object adapters store a reference to an instance of the existing class.


Therefore, an object adapteruses an existing class.


All adapter classes implement aninterface. In the class diagram shown in Figure 5-2,


the interface calledITargetdeclares a single method calledrequest( ). The class dia-


gram shows that a reference to an instance of theAdapteeclass is stored in the vari-


ableadaptee. When implementing therequest( )method, the adapter references this


instance.


Minimalist example of an object adapter


Example 5-1 through Example 5-4 show the implementation of an object adapter in


ActionScript 3.0. The different files are called:Adaptee.as(existing class),ITarget.as


(required interface),Adapter.as(adapter), andMain.as(client; also thedocument


class for the Flash document).


Figure 5-2. Class diagram of an object adapter


adpatee->specificRequest()

ITarget
request()

Adaptee
specificRequest()

Adapter
request()

adpatee
Free download pdf