动作:包级别的自省?或者一些其他的可插拔加载方案? [英] ActionScript: Package-level introspection? Or some other pluggable loading scheme?

查看:235
本文介绍了动作:包级别的自省?或者一些其他的可插拔加载方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编码了一些可口的业务逻辑和我来的情况是这样的:

I'm coding up some delicious business logic and I've come to a situation like this:

有许多规则( ruleA ruleB ,等...),它都遵循一个标准模式。我创建了一个规则接口,在 RuleA RuleB ,等等。

There are a bunch of rules (ruleA, ruleB, etc...) which all follow a standard pattern. I've created a Rule interface, and implemented it in RuleA, RuleB, and so on.

所以,现在我只是需要一种方法来加载它们。

So now I just need a way to load them.

现在,我使用的是图:

var rules:Object = {
    ruleA: new RuleA(),
    ruleB: new RuleB(),
   ...
};

然后调用它是这样的:

Then calling it like this:

function doStuff(whichRule:String, someData:Object):* {
    return rules[whichRule].applyTo(someData);
}

现在,该规则遵循一个标准的命名方案,他们是一包( foo.rules )的一部分... 有没有什么办法加载规则而不让他们某种名单?

Now, the rules follow a standard naming scheme, and they are all part of one package (foo.rules)... Is there any way to load the rules without keeping them some sort of list?

谢谢!

修改:为了澄清,希望在运行时发现可能的规则,所以我并不需要维护一个规则列表。例如:

Edit: To clarify, would like to discover the possible rules at runtime so I don't need to maintain a list of rules. For example:

function loadRule(name:String):Rule {
    import foo.rules;
    var rule:Class = foo.rules[name];
    return new rule();
}

除,当然,我不能索引到 foo.rules 命名空间......但是,这就是我希望能够做到。

Except, of course, I can't index into the foo.rules namespace... But that's what I'd like to be able to do.

推荐答案

您可以从一个字符串与flash.utils.getDefinitionByName(类名)引用类;

You can get a reference to a class from a string with the flash.utils.getDefinitionByName(className);

例如

def getRule(someValue: String) : Class{
    return getDefinitionByName("mybusiness.rules.Rule" + someValue);
}

在上面的例子中,你正在返回的类,但你也可以实例并返回对象。

In the example above you are returning a class, but you can also instantiate it and return the object.

但请注意,如果类,确定类名被编译到您的SWF这只会工作。如果没有别的地方在你的code你指的那类,否则将无法进行编译。这通常是达到了创造一些其他的一块code或构建系统引用可以传递给编译器。

Note however that this will only work if the class, identified by the class name is compiled into your swf. If no where else in your code you refer to that class, or else it won't be compiled. This is usually achieved creating references in some other piece of code or your build system can pass that to the compiler.

待办事项,其功能是在AS3第一类对象,所以,这取决于你的使用情况,您可以定义每个规则作为一个函数规则类,并通过了:

Do note, that functions are first class objects in AS3, so, depending on your use case, you can define each rule as a function to a Rule class and pass that:

def getRule(someValue: String) : Function{
    return new Rule()["theRuleName"];
}

这取决于你有多少逻辑,喜欢把到这些,多少共同code当然还有那些规则之间。

That depends on how much logic you'd like to put into those, and how much common code there is between those rules, of course.

这篇关于动作:包级别的自省?或者一些其他的可插拔加载方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆