Design Patterns

Design Patterns is a blog about my experiences learning UX/UI. I have spent years working in web based applications. I finally decided to start writing tutorials about that experience in hopes that it will help someone out along the way.

Starting Design Patterns 2

scott powers - Friday, December 10, 2010

There are a few terms that are important to understand as we get into design patterns a little more. Most of these terms apply to Object Oriented Programming (OOP), mainly because the reason I am studying design patterns is to become a better Object Oriented Programmer. The first term I want to understand better is Abstraction. Abstraction is knowing what you want in general, but not specifically. What does that mean? Well, in terms we deal with everyday, I may go shopping for a vehicle. I know I need a vehicle with plenty of room for the kids, it needs to be easy on gas, I would like for it to have a built in dvd player, a 6 cylinder engine, and front wheel drive. Those 'properties' could apply to several vehicles, but they are specific enough to understand that I am not looking for a Corvette. Once I get to the car lot (which is one of my least favorite places to go), I can give this abstract to the salesperson, and they could find several vehicles that fit that description. Then, I would narrow it down based on price, color, etc. The specifics would provide the concrete details of the specific vehicle (object) I want.

Starting Design Patterns

scott powers - Thursday, December 09, 2010

NOTE: This blog is more for my own record of learning/note taking. If it helps you out, great, but, it was never intended to be entertaining, or even interesting, it is mainly my thoughts/ideas/notes in my journey to learn more about Adobe Flash. I have returned, not completely to the beginning, but to the beginning of ActionScript 3.0 to try to help anyone who is just beginning their journey.

Art is pattern informed by sensibility. - Herbert Read

Source Files for Starting Design Patterns

I have read a great deal about design patterns. Going back this is where my journey began:

Design Patterns are 'tools for coping with constant change'1, but more to the point of this post, design patterns are the idea of looking at the big picture when you are developing code. The idea is to find sets of patterns in the code that you can then reuse. Why would you want to do this? I have read plenty, and have found many of the answers to this question a bit perplexing. I want a more concrete definition of design patterns for myself, so I can understand exactly what it is, and how I can use it to improve my programming skills.

One of the first things you need to do to learn how to do this type of programming in ActionScript 3.0, is take your scripts out of the timeline, off of movieclips and buttons, and move it into a class. What that means is this, you still use the Flash IDE (Integrated Development Environment), or basically the .fla file to compile your classes. You can still draw your symbols yourself, and create animations in Flash if you choose, but, your scripts will be held in a completely different file, an .as (actionscript) file.

So, if you choose to use the Flash IDE, there are a couple of things you will need to do. For simplicity's sake, we will create a folder called 'tutorial 1'. You can create it in some safe place on your machine so it is easy to find (desktop maybe). Now, open Flash, and create a new .fla file, save it in your 'tutorial 1' folder and name it 'ball.fla' or anything you like, the name of the .fla file will not matter. Okay, that is good, the next thing in order would be to create a new 'ActionScript 3.0 class'.



When you do this using the Flash IDE, you will be presented with the following panel:



You should fill it out as it is filled out above. Let's look quickly at this window. In this case, we want to use Flash Professional to create our class, not Flash Builder, we are using the Flash IDE for now. We also will leave the 'Don't Show Again' unchecked, you will see why in a bit. And, finally, we use a capital letter 'B' and lowercase for the rest (unless the class is more than one word, then we would use a capital letter to represent the first letter of each word). Flash prefers that you use capital letters to name a class.

For our first class, we will create a 'Ball' class. Click 'OK' and you will be presented with an .as file that looks like the following:



Flash CS5 creates everything you need for your class to start out.  Let's look at this code in detail:

package {
     public class Ball {
          public function Ball(){
               // constructor code
          }
     }
}


First, we use the keyword package. Packages bundle class definitions together in a way that facilitates code sharing and minimizes naming conflicts. In a sense, it lets us organize groups of classes. A package is the pathway through a series of nested subfolders at the end of which the class resides. If the class is meant to reside in the same folder as the .fla file that uses it, you can simply use the keyword 'package' as we did above. We will look at packages in greater detail in later lessons. For now, the 'package' declaration is necessary to create a class file that exists outside the .fla file. Next, Flash has declared  a public class 'Ball' which is the name we gave it when we filled in the 'Class Name' field in the 'Create ActionScript 3.0 Class' window. This is the name of our class. Flash also added the constructor method 'public function Ball()'. The constructor is a function that shares the same name as the class in which it is defined. Any code that you include in a constructor method is executed whenever an instance of the class is created with the new keyword. And then we have the closing brackets. Remember for every opening bracket, you need a closing bracket.

We need to extend the Ball Class by adding the following code:

package {
     import flash.display.Sprite;
     public class Ball extends Sprite {
          public function Ball(){
               // constructor code
          }
     }
}


When you add the 'extends Sprite' portion of the text, Flash will automatically add the 'import flash.display.Sprite' code above it. This is a new feature in Flash CS5, handy, I must admit, but it does make you a bit lazy. Anytime you use another class in your class (i.e. the 'Sprite') class, you must import it using it's package location (i.e. flash.display). In previous versions, you had to know that location (somewhat) by heart. Now Flash adds it when you add it within your code. By adding 'extends Sprite' you are basically telling the compiler that your new 'Ball' class will be able to do anything a Sprite can do. Our new subclass will use whatever a Sprite has access to, and it will also do a couple of specific things we tell it in our later code.

Now, we will go back to our .fla file and create a class using our drawing tools and 'create symbol' tool. Select the 'Oval Tool' and draw a circle on the stage. I used a red to black gradient fill for mine and made it 25px X 25px. Press cmd+F8 (mac) or F8(pc) while the circle fill and stroke are selected and you will get the following window:



Name your symbol ( I used 'RedBall'), make sure the drop down for 'Type' is 'MovieClip,  and select 'Export for ActionScript . You will notice that Flash will automatically create a class for you called 'RedBall' and it also sets a base class of 'flash.display.MovieClip'. What this means is that your ball you created on the stage is now it's own class, with it's own properties and methods. It also 'extends' the class MovieClip. By extending the class MovieClip, it will inherit all of the properties and methods of a MovieClip.

Now we want to do something with the RedBall, so, go into your 'RedBall' symbol, change the name of 'Layer 1' to 'RedBall' and add a keyframe in frame number 60. You can do this by highlighting or clicking in frame number 60 and then use cmd+F6 (mac) or F6 (pc), and you will now have a keyframe in frame 60. Go back to frame 1, and right click in it and select 'Create Shape Tween', which will give you an arrow from keyframe 1 to keyframe 60 and the frames in between will be colored light green (see below). Now, add another layer called 'scripts'. Your timeline should look like this:



Now, select frame 60 of the 'RedBall' layer, and move the movieclip on the stage to any other position on the stage (preferably one that is more than 100 pixels from it's original position). Now if you scrub the playhead back and forth, you will see the ball animate. If we placed the ball on the stage right now and compiled the movie, we would see the ball loop through the animation you just created. But, that is not our goal. Our goal in this tutorial, is to control our 'RedBall' class via our external .as file that is our 'Ball' class. So, the first thing we have to do is stop the RedBall class from animating. Using one of the older methods of ActionScript, we can put an action in a frame to control the RedBall class using it's 'stop()' method. So, click in frame 1 of the 'scripts' layer, and go to your actions panel by using cmd+F9(mac), or F9(pc), or, you can use the 'Window > Actions' menu selection from your main menu. In the 'Frame Actions' window, add the action 'stop();' without the single quotes.



This will stop the RedBall from animating when the swf file is loaded. At this point, you should have nothing on the main timeline. You can go to the main stage (Scene 1) and select the stage. Within your properties panel, you will see the following:



Add the name 'Ball' to the 'Class' input box. If you add the name Ball, and you can click back on the stage without getting any warnings, you have your files set up properly.



If you cannot, you need to make sure that you have a folder with both ball.fla and Ball.as in the same directory. The reason for this was kind of confusing at first. I originally wanted to 'import' classes by adding import statements in the first frame of my .fla file on the main stage, that is how I have always done things, by using 'import flash.display.MovieClip;' or 'import flash.events.Event;'.

I originally learned Flash way back, when you created your symbol (button or movieclip) gave it a name, and attached your action to the symbol, or placed it in a keyframe. Over the years, I had learned how inefficient that is because if something goes wrong, you spend a ton of time looking for your little snippets of code throughout your timeline, on movieclips, in frames, on buttons, etc. Then I moved on to creating my interface using the drawing tools and then placing instances on the stage and naming them. With that, I could keep all of my code in the first frame of the main timeline, and use dot syntax to drill into whatever I wanted to drill into and control it with actions. This seemed much more efficient, and kept my code in one place. The problem with this method is, when you have several items on stage that you want to control, or a large application, you can have hundreds, even thousands of lines of code in that first frame, and it becomes cumbersome to find the specific code to control your items.

So, now Flash has helped me learn to break down my code into more modular, simple pieces (classes) that control one minor part of my application. This way, if an item breaks, I can go to that class and look through 20 or 30 lines of code, rather than hundreds. It also makes it easier to 'reuse' code, if I want to create a class that loads items into my swf (a Loader class) I can create that generically, put the generic functionality, methods, and properties in it, and then 'extend' it to load whatever I want, xml, bitmaps, swf's, etc. The only thing I need to instantiate my classes is my 'Document Class' which in this case is the 'Ball.as' file that we just attached using the 'Properties' panel of our ball.fla document. I can control my RedBall on the stage, and if I want to add more to it, I can add classes and import them through my 'Ball.as' class.

So, now we have everything in place, all we need to do is put some scripting in our 'Ball.as' Class. So, go back to 'Ball.as' and add the following code:

package  {
    
    import flash.display.Sprite;
    
    public class Ball extends Sprite{
        private var redBall:RedBall;

        public function Ball() {
            // constructor code
            redBall=new RedBall();
            redBall.x = 50;
            redBall.y = 50;
            addChild(redBall);

        }

    }
    
}


Let's break this down. First of all, Sprite is kind of new (not really, but I didn't use it much before, I always used MovieClips). A Sprite is basically a MovieClip without a timeline. If you look on Adobe livedocs, you can see that a Movieclip inherits from a Sprite. So a sprite is one up on the food chain of Display Objects within the Flash Display Object hierarchy. So, we import the Sprite class since our Ball class extends Sprite. By extending Sprite, we get all of the functionality of a sprite and a movieclip.

Next, we create a property, or a var and call it redBall. It is of type 'RedBall' Class, which is basically our RedBall in the library of our .fla file. Since we set it up to 'Export for ActionScript', we made it it's own class and it inherits from MovieClip.



Then comes our constructor, which instantiates our ball on the stage:

public function Ball() {
            // constructor code
            redBall=new RedBall();
            redBall.x = 50;
            redBall.y = 50;
            addChild(redBall);
}


We set our var to equal a new RedBall, and then give it coordinates for the stage, and finally, add an instance of it to the stage using the 'addChild' method. If you test the movie now, you will see an instance of the redBall on the stage at x=50 and y=50.

Now, to control our RedBall class using our Ball class, we will add one more line of code:

package  {
    
    import flash.display.Sprite;
    
    public class Ball extends Sprite{
        private var redBall:RedBall;

        public function Ball() {
            // constructor code
            redBall=new RedBall();
            redBall.x = 50;
            redBall.y = 50;
            addChild(redBall);
            redBall.gotoAndPlay(2);
        }

    }
    
}


Now, test the movie, and you will see the ball move across the stage. You can download the source files for this tutorial by clicking this link.  The significance of this tutorial is that you can take advantage of the Flash IDE to create a symbol, make it a class, and instantiate it just like any other class in ActionScript 3.0. It doesn't have to be on stage, you can put it there dynamically. How does this apply to design patterns? You can create your classes visually using the Flash IDE, and turn them into classes from within the IDE, and then instantiate them like any other class you would instantiate using ActionScript 3.0. For someone like me, who is a visual designer first, and a programmer second. I like to have this option available when I create any new application.





1William Sanders and Chandima Cumaranatunge, ActionScript 3.0 Design Patterns (Sebastopol, CA: O'Reilly Media, Inc. 2007) 1


1