Eamonn Faherty

Actionscript3 Design Patterns:Factory Method

by eamonn on Nov.17, 2009, under development

Background Reading
The creation method pattern

The Problem?
You want to use objects that are created else where and are of a set type but the implementations may vary.

Examples?
SocketManager, or any thing that needs to be replace during unit testing.

How?
The constructor of my complex object:

public class CharacterFactory {

	public static var factory : NonPlayerCharacterFactory;

	public static function getAPlayer() : IPlayer {
		return factory.getAButton();
	}
}

The using of the creation method:

var player:IPlayer = CharacterFactory. getAPlayer();

Why is it good?
• It is easy to understand; it is a simple pattern that needs little extra code. It builds on the singleton pattern, which is well known.
• You can get objects without knowing how they are created or where they come from.
• You can share objects without the users of the factory knowing the objects are shared.

Why is it bad?
• It is confusing to read code where objects are not being created directly.
• Debugging is hard, as you have to know what was in the factory when you used it in order to know what object you have.

Further Reading
Read about the IOC pattern.

More
Factories are great! They allow you to define scope for your application. This means that you can set a testing scope when you are running unit tests. The involves setting the factories used in your factory to a test factory which provides test doubles. Changing the scope of the factories outside of your application means that you test your code without making any special changes.

Related posts:

  1. Actionscript3 Design Patterns:Creation Method Background Reading The factory method pattern The Problem? You have...
  2. Actionscript3 Design Patterns:The Multiton Background Reading Read about the singleton The Problem? You want...
  3. Actionscript3 Design Patterns:The Singleton Background Reading None The Problem? You want to ensure you...
  4. Design Patterns for Actionscript 3 I recently did my first public talk! It was at...

Related posts brought to you by Yet Another Related Posts Plugin.

:,

blog comments powered by Disqus

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!