O'Reilly logo

Agile Enterprise Application Development with Flex by Tony Hillerson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Class Factory

Flex offers you various ways to create an instance of a component. For example, in MXML, you can create an instance of MyObject and initialize its property description as follows:

<comp:MyObject id="order" description="Sony TV" />

You can achieve the same result (i.e., create an instance of MyObject and initialize the description) in ActionScript:

var order:MyObject = new MyObject();
order.description="Sony TV";

This code works fine as long as MyObject is the only possible component that can be placed in this particular screen location. But what if you need more flexibility—for example, under certain conditions you need to create either MyObject or HisObject at this location?

Instead of using the new operator, you can introduce a class with a function that will build different objects for your application based on a specified parameter. In this case, you need to implement the Class Factory design pattern—the object that will create and return either an instance of MyObject or HisObject.

You can easily find code samples of how to create class factories. Some of them are very basic, so that you just provide the name of the object you need to a factory method that has a switch statement, and it returns the proper instance of the object based on the provided name. More advanced factories are programmed to interfaces, which allows you to add new types of objects to the factory without the need to use and modify the switch each time a new object type is introduced.

A Class Factory ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required