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 ...
Get Agile Enterprise Application Development with Flex now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.