user3111941
user3111941

Reputation: 11

Should an Init method be in getInstance or the constructor?

I have getInstance and a constructor in the same class, but I am not sure where I put my Init method.

public class UploadService {   
    private Eng mEng;
    private Context mContext;
    private static UploadService INSTANCE;
    private String appDir;

    public static UploadService getInstance(Context context) {
        if (null == INSTANCE) {
            INSTANCE = new UploadService(context);
        }
        return INSTANCE;    
    }

    public UploadService(Context context) {
        this.mContext = context;
        appDir=V8Utils.getAppDir(context);
    }

    public void init(Context cxt) {
        mEng = new Eng(cxt);
        mEng.init(appDir);

    }
}

Upvotes: 1

Views: 351

Answers (1)

Vikdor
Vikdor

Reputation: 24134

I would

  • mark init() as private method.
  • call it in the constructor as it is initializing the state of UploadService object using the Context object.

I mean:

public UploadService(Context context) {
    this.mContext = context;
    appDir=V8Utils.getAppDir(context);
    init(context);
}

private void init(Context cxt) {
    mEng = new Eng(cxt);
    mEng.init(appDir);

}

Upvotes: 2

Related Questions