Where’s the Clone()?
The next design pattern I plan to tackle in ActionScript 3.0 is the Prototype Design Pattern. Getting started I ran into the clone() method in other languages like C#. As usual, that wasn’t much help. To my surprise, I found that several classes in ActionScript 3.0 have a clone() method such as the Rectangle class. However, while perfectly functional, cloning a rectangle with origins in the flash.geom namespace isn’t exactly what I had hoped for. (There’s no clone() method in the Shape class where I could make lots of clones of rectangle shapes I could put on the stage.) What I wanted was a way to clone objects.
Borrowing from Java
Buried in the Adobe ActionScript 3.0 Live Docs is a little note about cloning arrays. (see http://livedocs.adobe.com/flex/3/html/10_Lists_of_data_6.html) Using a method commonly found in Java programs, the note indicates that a deep copy clone is possible using this method. One can use concat() or slice() with no arguments to make a shallow copy. In most cases, GoF note that shallow copies will work fine, but for more complex structures a deep copy is required.
The docs list the key method as the following:
import flash.utils.ByteArray; function clone(source:Object):* { var myBA:ByteArray = new ByteArray(); myBA.writeObject(source); myBA.position = 0; return(myBA.readObject()); }
That’s a nice little piece of code and simple to understand. The clone() method creates a ByteArray that writes the object (an array) and then returns it by reading the object it just wrote. Moreover, it’s a deep copy and as such a true clone in that all of the parts are delivered and not just pointers.
Continue reading ‘ActionScript 3.0 Clone: A Prelude to the Prototype Design Pattern’




Recent Comments