0

I have a class which contains the following method to place an object on the stage.

public function createBox()
{
    var box:Ball1 = new Ball1();
    addChild(box);
    box.addEventListener(Event.ENTER_FRAME, boxF);
}

What I would like to do is to is pass an object name to the method, and load that object instead, thus allowing me to use the same method for different objects.

A non-working example:

public function createBox( obj )
{
    var box:obj = new obj();
    addChild(box);
    box.addEventListener(Event.ENTER_FRAME, boxF);
}

Is this possible?

Thanks

2 Answers 2

3

A more agile version of the existing answer is to use getDefinitionByName(), which allows you to construct a class based on an input string.

Using this function, you can rewrite the method to something like this:

public function produce(className:String):*
{
    var type:Class = getDefinitionByName(className) as Class;
    return new type();
}


Advanced:

To make this stricter and more maintainable (make it so only certain factories can create certain classes), you can use an interface to build a relationship between a given factory and the classes it can produce. A small example of this follows below.

Say a factory, EnemyFactory, creates objects that you would consider to be enemies in a game. We don't want to be able to create things like pickups, particles and other non-enemy type objects. We can create an interface IEnemyProduct which is implemented by classes that the EnemyFactory is allowed to create. The interface could be as simple as:

public interface IEnemyProduct{}

Which would be implemented by any enemy classes. The EnemyFactory's produce() function can then be modified to a more readable version, like this:

public function produce(enemyClassName:String):IEnemyProduct
{
    var type:Class = getDefinitionByName(enemyClassName) as Class;
    return new type() as IEnemyProduct;
}

In this case, produce() will return null if the produced class does not implement IEnemyProduct. The goal here is to make it obvious which factories are responsible for which objects, which is a big advantage once the project becomes larger. The use of an interface rather than a base class also means you can implement multiple interfaces and have the class produced by multiple factories.

Sign up to request clarification or add additional context in comments.

Comments

0

You could maybe use a simple factory, or something similar:

  public class Factory
  {
      public static function produce(obj:String)
      {
          if (obj == "obj1")
          {
              return new obj1();
          } else if (obj == "obj2") {
              return new obj2();
          }
      }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.