我有一个班级,目前非常混乱/重复:
public class AvFramework extends Object
{
// vars
private var _handler:AvHandler;
private var _keyboard:AvKeyboard;
private var _manager:AvManager;
/**
* Constructor
*/
public function AvFramework()
{
_handler = new AvHandler();
_keyboard = new AvKeyboard();
_manager = new AvManager();
// attach
_handler.framework = this;
_keyboard.framework = this;
_manager.framework = this;
}
/**
* Getters
*/
public function get keyboard():AvKeyboard{ return _keyboard; }
public function get manager():AvManager{ return _manager; }
}
这个类只需要使用越来越多的类,我真的不想像上面那样拥有3个巨大的列表。
有没有办法动态地执行上述操作 - 可能在字符串循环中使用getDefinitonByName()
来表示我想要创建的类。
我还希望这些属性是只读的,并且可以通过framework.myDynamicVarHere
访问。
我正在思考这些问题:
dynamic
,以便我可以通过this["var"] = new Blah();
我的想法的快速摘要:
var required:Object =
{
keyboard: "avian.framework.background.AvKeyboard",
manager: "avian.framework.background.AvManager",
handler: "avian.framework.background.AvHandler"
};
var i:String;
for(i in required)
{
var Req:Class = Class(getDefinitionByName(required[i]));
this[i] = new Req();
AvFrameworkObject(this[i]).framework = this;
}
我不确定如何才能使这些只读。
答案 0 :(得分:4)
您可以使用Proxy类来控制get / set调用并完成Eugeny89的答案。 查看http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Proxy.html或http://blog.joa-ebert.com/2007/05/25/as3-proxy-example/
var required:Object =
{
keyboard: "avian.framework.background.AvKeyboard",
manager: "avian.framework.background.AvManager",
handler: "avian.framework.background.AvHandler"
};
...
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public dynamic class AvFramework extends Proxy {
private var holder: Object = {};
public function AvFramework() {
var i:String;
for(i in required)
{
var Req:Class = Class(getDefinitionByName(required[i]));
var name = //get Class name from required[i] e.g. AvKeyboard from avian.framework.background.AvKeyboard
holder[name] = new Req();
holder[name].framework = this;
}
}
flash_proxy override function getProperty( name: * ): *
{
return holder[name];
}
flash_proxy function setProperty(name:*, value:*):void
{
// Do nothing
}
}
使用此代码,当您执行myAvFrameworkObj.something时,getProperty()将自动调用,并从“name”变量获取属性名称。
答案 1 :(得分:1)
也许你会尝试在对象中包装那长长的classws列表:
var required:Object =
{
keyboard: "avian.framework.background.AvKeyboard",
manager: "avian.framework.background.AvManager",
handler: "avian.framework.background.AvHandler"
};
...
public class AvFramework extends Object {
private var holder: Object;
public function AvFramework() {
holder = new Object();
var i:String;
for(i in required)
{
var Req:Class = Class(getDefinitionByName(required[i]));
var name = //get Class name from required[i] e.g. AvKeyboard from avian.framework.background.AvKeyboard
holder[name] = new Req();
holder[name].framework = this;
}
}
public var getHolder() { return holder; }
}
你可以参考例如AvKeyboard
framework.getHolder()["AvKeyboard"]
或framework.getHolder()[someVar]
required
。因此holder
中的所有类都是只读的,因为{{1}}是只读的。
希望能帮到你!