我怎样才能改进这个单身人士?

Jim*_*Jim 3 java oop singleton design-patterns

我有一个将作为单身人士的课程.
该类将获取一个文件作为构造函数的一部分.之后,课程准备好了.
因此,目前我使用双重检查锁定惯用法并通过static getInstance()经典方式获得单例的实例.
我的问题是,目前我经常这样做:

MySingleton.getInstance(theFile);

并且theFile仅在第一次构造单身时才需要.在那之后,即一旦构建了单身人士,我就不需要传递theFile.
我该怎么办?
我想创建一个MySingleton.getInstance(); 但仍然无法工作,因为调用者必须MySingleton.getInstance(theFile); 第一次调用构造一个有效的类.
我怎样才能更好地设计它?

Boh*_*ian 9

声明一个init()使用该文件处理初始化的方法.

简化getInstance()返回实例,但抛出一个尚未调用的IllegalStateExceptionif init().

例如:

public class MySingleton {

    private MySingleton INSTANCE;

    // private constructor is best practice for a singleton 
    private MySingleton(File theFile) {
        // initialize class using "theFile"
    }

    public static void init(File theFile) {
        // if init previously called, throw IllegalStateException
        if (INSTANCE != null)
            throw new IllegalStateException();
        // initialize singleton 
        INSTANCE = new MySingleton(theFile);
    }

    public static MySingleton getInstance() {
        // if init hasn't been called yet, throw IllegalStateException
        if (INSTANCE == null)
            throw new IllegalStateException();
        return INSTANCE;
    }

    // rest of class
}
Run Code Online (Sandbox Code Playgroud)

请注意,虽然这不是线程安全的,但只要init()在服务器启动过程中尽早调用,竞争条件确实很少(如果有的话).