This question is in the context of an Android application written in Java.
I have this class which performs a specific action and returns the result of such action with a callback implemented in the activity where it was called. This class depends on the current activity reference. This is not a singleton because this class can be called from different activities.
One obvious solution could be something like this:
public class MyClass {
private final Activity mActivity;
private Callback mCallback;
public MyClass(Activity activity, Callback callback) {
mActivity = activity;
mCallback = callback;
}
public void initialize() {
// do something...
mCallback.onFinished();
}
public interface Callback {
void onFinished();
}
}
public class MainActivity implements MyClass.Callback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyClass(this, this).initialize();
}
@Override
public void onFinished() {
// do something...
}
}
This works and it's fine, I guess. But I really don't like the new MyClass(this, this).initialize();
line. That new
just doesn't feel right.
This is when I came up with a slightly different solution and with a small variation on the parameters:
public class MyClass {
private final Activity mActivity;
private MyClass(Activity activity) {
mActivity = activity;
}
public static MyClass with(Activity activity) {
return new MyClass(activity);
}
public void initialize(Callback callback) {
// do something...
callback.onFinished();
}
public interface Callback {
void onFinished();
}
}
public class MainActivity implements MyClass.Callback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyClass.with(this).initialize(this);
}
@Override
public void onFinished() {
// do something...
}
}
Does the exact something, but instead of explicitly creating an instance with the new
keyword, it is created implicitly with the static with()
method.
Maybe this is just a matter of preference but IMO this feels more natural than using the new
keyword. Perhaps the with
and initialize
names are not the best ones, but what do you guys think of this?
Do you have a third alternative?
public static MyClass with(Activity activity) { return new MyClass(activity); }
, though note that all you really did was push thenew
somewhere else.