This might just be a question of personal taste and workflow, but in case it's more than that, I feel I should ask anyway.
In Java, what differences are there between creating an instance via constructor and via a static method (which returns the instance)? For example, take this bit of code from a project I'm working on (written up by hand at time of posting, so some shortcuts and liberties are taken):
Plugin main;
Map map;
public Handler(Plugin main) {
this.main = main;
}
public static Handler init(Plugin main) {
Handler handler = new Handler(main);
handler.createMap();
}
public void createMap() {
this.map = Maps.newHashMap();
}
In cases like this, what would the difference be between using
Handler handler = new Handler(this);
and
Handler handler = Handler.init(this);
in the Plugin class, besides the fact that createMap() runs only in the latter because it's not called in the constructor?
To clarify, in this case, Plugin is considered the main class.
I know enough Java syntax to be able to write intermediate-level plugins, but not enough about Java itself to know the difference between these two ways of doing this.
EDIT: For instance, the Maps class that I used to create the Map uses a static factory method (I hope I'm using that term correctly) called using the class instead of an object.
解决方案
The difference is a static factory method is more flexible. It can have all sorts of ways to return an instance. It can do other side stuff. It can have a more descriptive name. It can be invoked by its simple name (e.g. foo(args)) by static import or inheritance.
The constructor call is more certain - the caller knows exactly what's happening - a new instance of that exact class is created.