我正在創建一個實用程序類,它將用於(除其他之外)創建綁定到當前線程的新org.mozilla.javascript.Context
對象。我有一個單一的全球JavaScript範圍,可能有幾個導入/初始化語句,等等。在Java中創建靜態單例模式
我希望外部類能夠通過簡單地使用Utility.getContext()
來檢索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;
}
}
似乎你不有鎖定上下文和範圍的單身人士,所以你不能保證那些人會成爲單身人士。 – Arcymag 2012-07-18 04:45:20
也許更適合[codereview](http://codereview.stackexchange.com/)。 – 2012-07-18 04:45:22
Java和JavaScript結合在一起? Java的ception。 – 2012-07-18 04:56:12