Program to Interfaces over Implementations | 47
Using Complex Interfaces
As you saw in Example 1-36, the program typed the instances to the implementation
and not the interfaces as was done in Example 1-20. This was caused by the key
methods being part of classes that implemented an interface and extended a class.
Because of the way in which the different display objects need to be employed, this
dilemma will be a common one in using Flash and ActionScript 3.0. Fortunately, a
solution is at hand. (The solution may be considered aworkaroundinstead of the
correct usage of the different structures in ActionScript 3.0. However, with it, you
can create methods that require someDisplayObjectstructure and program to the
interface instead of the implementation.)
If the interface includes a method to include aDisplayObjecttype, it can be an inte-
gral part of the interface. BecauseSpriteis a subclass of theDisplayObject, its inclu-
sion in the interface lets you type to the interface when the class you instantiate is a
subclass ofSprite (or some other subclass of theDisplayObject, such asMovieClip.)
To see how this works, the application made up of Example 1-39 and Example 1-40
creates a simple video player. TheVidPlayerclass builds the structural details of the
video playing operations. To do so requires that it subclass theSpriteclass. By plac-
ing a getter method with aDisplayObjecttype in theIVidinterface, the application
sets up a way that the client can program to the interface.
The implementation of the IVid interface includes a key element. The
displayObject( )function is implemented to theDisplayObjectclass in building the
VidPlayer class.
Example 1-39. IVid.as
package
{
import flash.display.DisplayObject;
public interface IVid
{
function playVid(flv:String):void;
function get displayObject( ):DisplayObject;
}
}
Example 1-40. VidPlayer.as
package
{
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.display.Sprite;
import flash.display.DisplayObject;