我正在创建一个实用程序类,它将用于(除其他外)创建一个org.mozilla.javascript.Context
绑定到当前线程的新对象。我有一个单一的全局 JavaScript 范围,它可能有几个导入/初始化语句等。
我希望外部类能够通过简单地使用Utility.getContext()
and来检索 Context 对象和 Scope 对象以供将来执行Utility.getScope()
,而不必显式使用该getInstance()
函数。单例模式是必要的,因为上下文和范围都需要是单个实例。
下面的代码有意义吗?
public class Utility {
private static Utility instance;
private static ScriptableObject scope = null;
private Utility() {}
private static Utility getInstance() {
synchronized (Utility.class) {
if (instance == null)
instance = new Utility();
return instance;
}
}
private static Context getSingletonContext() {
Context context = Context.getCurrentContext();
if (context == null)
context = Context.enter();
if (scope == null) {
scope = new ImporterTopLevel(context);
Script script = context.compileString("Global JavaScript Here","Script Name",1,null);
script.exec(context,scope);
scope.sealObject();
}
return context;
}
public static Context getContext() {
return getInstance().getSingletonContext();
}
public static Scriptable getScope() {
Scriptable newScope = getContext().newObject(scope);
newScope.setPrototype(scope);
newScope.setParentScope(null);
return newScope;
}
}