English 中文(简体)
Actionscript 3:从解析的XML文件中创建变量对象并分配类
原标题:
  • 时间:2009-04-07 20:24:43
  •  标签:

I ve set up an XML file with names of objects that will be contained in a fla/swf library. I wish to position the objects on the stage using an XML file that can be quickly modified without having to recompile the fla/swf file. Of course, positioning can only be accomplished when the objects are instantiaed and added to the stage. The problem is passing the parsed XML file name/class paring data into the var creation programatically.

XML文件包含对象名称和类:示例如下:

<objects>
   <object name="myBall" class="Ball"/>
</objects>

The XML file parses correctly and I ve set up a ...for...each loop to assign the name/class to each object. The problem is with the proper syntax to input the name/class paring, something similar to the following:

var object.@name:object.@class = new object.@class();

我是被这件事弄糊涂了,还是只是暂时无知**

最佳回答

只要快速跟进,就有一种非常直接的方法可以保持灵活性:

var xml:XML = <object name="myBall" class="Ball">;

// Looks up for a defined symbl/definition with the name  Ball     
var Def:Class = getDefinitionByName(xml.@class);

// Creates the instance of the Ball
var instance:* = new Def();

// in case you want to assign a name to the node as a reference on the display list :
addChild(instance).name = @xml.name;
问题回答

我不确定你想做什么。

是否要创建一个名为myBall、类型为Ball的对象?

var object:Object = new Object();
object[objects.name] = createNewClass(objects.class);

...

function createNewClass(var name:String):Object
{
    if(name == "Ball")
        return new Ball();
    ...
}

不确定这是否是你想要做的。我不知道是否有办法只通过文本创建一个新的球,如果有人知道如何做到这一点,我也想知道如何做到。

根据您的要求,听起来您正在尝试一种Factory模式(Factory方法),其中类负责根据外部源提供的信息动态生成对象。

我建议研究一下Flex和ActionScript的设计模式。我还没有用Flex编写过Factory方法,但它不会比Java难太多,Java也不错。

总的来说,我希望你的程序是这样的:

  1. Your XML describes the object which will be generated (class type, params, etc.). Your example appears to show this.
  2. You have an XSD which can verify the XML file conforms to your program s expectations -- if it doesn t, an appropriate error would be outputted. I would highly recommend something along these lines for validation: you need to have a mechanism which guarantees the XML is correct.
  3. You ve abstracted the values you are expecting to be in the XML. I would recommend using Enums or static/constant String values in a separate utility class.
  4. You have a Factory class whose sole responsibility is to take in the XML data, generate the objects based upon the contents, and return it to whoever needs it.

第四点,显然是你在看什么,或者(我认为)。CookieOfFortune的例子显示了这个工厂方法可能会是什么样子。然而,我建议您也将字符串值抽象为变量或枚举:

...
var BALL_CLASS_TYPE:String = "Ball";
...
function createNewClass(var name:String):Object {
    if (name == BALL_CLASS_TYPE)
        return new Ball();
}

然而,您的第一个参数让我感到困惑。听起来您正试图创建一个动态对象,该对象具有动态命名的引用(例如var<;x>;:对象,其中<;x>;被定义为XML中的数据)。我甚至不知道这是否可能。我当然认为没有必要。





相关问题
热门标签