Actionscript3 Design Patternscreation Method

Title: Actionscript3 Design Patterns:Creation Method Date: 2009-11-11 16:17 Author: eamonnfaherty Category: development Tags: actionscript3, creation method, design patterns Slug: actionscript3-design-patternscreation-method

Background Reading
The factory method pattern

The Problem?
You have a complex object, which has a lot of arguments in its constructor or you always want to construct the object using different sets of parameters.

Examples?
Socket Manager

How?
The constructor of my complex object:

public function ComplicatedButton(colour:uint, mouseOverColour:uint, mouseOutColour:uint) {
    _mouseOverColour = mouseOverColour;
    _mouseOutColour = mouseOutColour;
    setUpGraphics(colour);
addEventListeners();
}

The using of the creation method:

var redButton : ComplicatedButton = ComplicatedButton.getRedButton();
var blueButton : ComplicatedButton = ComplicatedButton.getBlueButton(); 

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.
• Anyone using one of the creation methods to create the object is guaranteed to have an object in an identical state as the other users of the method.
• Objects that complicated or a lot of constructor parameters can be simplified.

Why is it bad?
• The class now has two responsibilities, the main purpose of the class plus the instantiation of its instances.
• The class can often grow in size as the creators in declared inside the class. This makes the class harder to read for a developer.

Further Reading
Read about the factory patterns.

More
Creation methods are a great first move towards using factories. Their concept is easy to grasp and doesn’t require much extra code. The class can grow quite big, quite quickly but it is up to you to spot when the acceptable size has been passed for you to put your refactoring hat on. I would use them when I have a graphical component that accepts integer colours as parameters or when I have components that need a lot of initial set up. In the example above I have colours specified as integers. To ensure that all of the buttons considered to be red or blue are the same shades of red or blue I protect users of my ComplicatedButton by adding creation methods with the colours hard coded. Once I have more than one group of setups I would refactor, replacing the creation method with a factory method.

Published: November 11 2009

  • category:
  • tags:
blog comments powered by Disqus