ActionScript 3.0 Lazy Initialization and the Factory Method Design Pattern

Lazy Initialization
Just be careful not to call factory methods in the Creator’s constructor—the factory method in the ConcreteCreator won’t be available yet. (page 112)
The comment was directed at some issues in C++ which may or may not have any bearing on ActionScript 3.0, but just in case it did, I continued reading. The point being made was you can avoid these problems by accessing products only through accessor operations that create products on demand. So what are accessor operations? Generally these are public methods that you can call to initiate creation of a product.
Time Out! Before we get too far ahead of ourselves, you can download all of the .as files for the Factory Method example by clicking the following button:

The example is a simple one that creates three different shapes—ellipse, rectangle and triangle. Figure 1 shows how the Client arranged them to display a house in front a a pond with a cloud overhead:

Figure 1:Triangle, Ellipse and Rectangle Products
The program uses concrete creators to fetch shapes. The Client makes requests that size, color, and position the shapes.
Don’t Enslave Your Constructor Functions
This issue of the constructor functions reminded me of a post by Miško Hevery, the guy at Google who helps set Google’s programming standards. One of the key flaws in a program is where the constructor does real work. Besides violating the single responsibility rule, Miško goes on to explain the tell-tale signs that one has used his constructor function with outrageous disregard for both agile programming and loose coupling. As a result of reading Hevery’s work, a year or so ago, I began to seriously gear back on using a class’ constructor function; primarily by not including one in most of my classes. (My Client class is a glaring exception to the rule.) I’d usually have just the properties and operations (methods, functions) that I needed. The properties would initialize themselves—sort of. They’d be given an ID and then typed and that was all. The child classes could then use them in operations. Whenever I needed something, the Client would type a request to the interface (including abstract classes) and then make a request through concrete method in an operation. With the Factory Method, I make requests to the ConcreteCreator through the abstract Creator class.
In returning to GoF, they point out,
Instead of creating the concrete product in the constructor, the constructor merely initializes it to 0. (Page 112)
In this discussion, they note that Factory methods in C++ are always virtual functions. WTF?! (What’s That Function?!) Simply stated, any function that can be overridden in the child classes is a virtual one. Well, we can do that in ActionScript 3.0. In fact, that’s what we do in creating Abstract classes. (Why we can override and yet not have real Abstract classes is still a mystery to me.)

Bill Sanders
Recent Comments