在Java中创建静态Singleton模式

Creating Static Singleton Patterns in Java

本文关键字:Singleton 模式 静态 创建 Java      更新时间:2023-11-25

我正在创建一个实用程序类,该类将用于创建绑定到当前线程的新org.mozilla.javascript.Context对象。我有一个单独的全局JavaScript范围,可能有几个导入/初始化语句等。

我希望外部类能够通过简单地使用Utility.getContext()Utility.getScope()来检索Context对象和Scope对象以供将来执行,而不必显式地使用getInstance()函数。singleton模式是必要的,因为上下文和作用域都需要是单个实例。

下面的代码有意义吗?

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;
    }
}

1.将此公开

public static Utility getInstance()

2.不需要使类中的所有方法都是静态的,除了这个getInstance()方法。

3.当您试图访问其他类中该类的singleton对象时,请按此方式执行。

Utility ut = Utility.getInstance();

这就是为什么您不需要将Utility类中的方法设置为静态的,除了getInstance()

4.有三种方法可以获得Singleton

i同步方法

ii带有双重检查锁定的同步语句。

iii在定义时初始化静态对象引用变量。。

例如:

在定义时初始化静态对象引用变量

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
    }