简体   繁体   中英

AS3 Dynamically create an instance of an object

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

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.

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();
          }
      }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM