use*_*553 1 javascript java singleton scope
我正在创建一个实用程序类,它将用于(除其他外)创建一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
1.公开
public static Utility getInstance()
Run Code Online (Sandbox Code Playgroud)
2.不需要将类中的所有方法都设为静态,除了这个getInstance()方法。
3.当你试图在其他类中访问这个类的单例对象时,这样做。
Utility ut = Utility.getInstance();
Run Code Online (Sandbox Code Playgroud)
看到这就是为什么您不需要将 Utility 类中的方法设为静态除了 getInstance()
4.获取Singleton 的三种方式,
一世。同步方法
ii. 带有双重检查锁定的同步语句。
三、在定义时初始化静态对象引用变量..
例如:
在定义时初始化静态对象引用变量
private static Utility instance = new Utility();
private Utility() {}
private static Utility getInstance() {
return instance; // WILL ALWAYS RETURN SINGLETON
// REFER HEAD FIRST DESIGN PATTERN BOOK FOR DETAILS
}
Run Code Online (Sandbox Code Playgroud)