10.12.2012 Views

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example 5-4. Main.as (continued)<br />

}<br />

}<br />

public function Main( )<br />

{<br />

var target:ITarget = new Adapter( );<br />

target.request( );<br />

}<br />

The client class Main creates an instance of the adapter class and calls the method<br />

request( ) defined in the ITarget interface. The client sees only the interface that’s<br />

implemented by the adapter. Object adapters are like traffic cops, as they intercept<br />

method calls and decide what to do with them. Some of the method calls are directed<br />

to the appropriate methods in the Adaptee class. The Adaptor class keeps tight control<br />

of access to the existing class by implementing only the ITarget interface. The client<br />

doesn’t even know that the adapter’s using an existing class. The Adaptee class could<br />

have many public methods and properties that aren’t accessible through the adapter.<br />

Because the Adaptor class creates an instance of the Adaptee class, there’s tight<br />

coupling between them. This doesn’t allow the adapter to use a subclass of Adaptee<br />

or use a totally different existing class without modifying existing Adapter code.<br />

Using a parameterized adapter class<br />

A variation on the previous example of the adapter is to require the client to pass an<br />

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

parameterized constructor in the adapter class. The following changes are needed in<br />

the Adapter class constructor.<br />

public function Adapter(a:Adaptee)<br />

{<br />

this.adaptee = a;<br />

}<br />

This is desirable in many cases, as it reduces the coupling between the Adapter and<br />

Adaptee classes, providing more flexibility. However, this puts the burden on the client<br />

to create an instance of Adaptee class and pass it to the adapter.<br />

var adaptee:Adaptee = new Adaptee( );<br />

var target:ITarget = new Adapter(adaptee);<br />

The disadvantage of doing it this way is that the existing class is no longer hidden<br />

from the client. The client creates the instance of Adaptee that is passed to the<br />

Adaptor. This could potentially cause disruption if the client inadvertently manipulates<br />

the Adaptee instance.<br />

Class Adapters<br />

When the adapter uses inheritance to access an existing class, it’s known as a class<br />

adapter. The adapter class extends the existing class and has an is-a relationship with<br />

Object and Class Adapters | 181

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!