AS3 Factory Pattern Implementation

Occasionally when developing Flex applications you will run into a situation where the application calls for certain objects to be instantiated without knowing what type of objects they will be. For example, consider the following scenario: You are building a store in which there are multiple products available. You have created various value objects that represent each product in the store, but you have no way of knowing which products a user will select at runtime, therefore you have no way of knowing which VO’s to instantiate? This is a good example of where implementing the Factory Pattern comes in handy.

In case you are not familiar with a Factory Pattern let me give you a quick overview. The Factory Pattern is a creational pattern that models an interface for creating an object which at runtime delegates instantiation to it’s subclasses. This is called a factory pattern since it is intended to “Manufacture” objects. When using the factory pattern your code is loosely coupled since it eliminates the need to embed logic and application specific classes into your code.

For example, you can just as easily add logic to your code that determines which class to instantiate based on the product selected. The only problem with this approach is that you may not want to have the product classes available to the application in general, but rather provide a specific class which is responsible for deciding which class to instantiate, and then return the object to the application. This way your application can stay loosely coupled and the product classes can be abstracted from the application. This approach encourages encapsulation and delegation which is always a good thing in Object Oriented Programming.

I developed a basic sample application which implements the Factory pattern in ActionScript 3 that you can view here.

You can also click here to view the source code as well as the ASDocs

{ 1 comment to read ... please submit second! }

  1. Thanks a lot. This example helped me to understand the Factory design pattern.

{ 0 Pingbacks/Trackbacks }