问题描述
这可能只是个人喜好和工作流程的问题,但是如果不止于此,我还是应该问一下.
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.
在Java中,通过构造函数和通过静态方法(返回实例)创建实例之间有什么区别?例如,从我正在处理的项目中获取以下代码(在发布时手动编写,因此采用了一些快捷方式和自由):
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<int, int> 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();
}
在这种情况下,使用
Handler handler = new Handler(this);
和
Handler handler = Handler.init(this);
在Plugin类中,除了createMap()
仅在后者中运行是因为在构造函数中未调用它之外?
in the Plugin class, besides the fact that createMap()
runs only in the latter because it's not called in the constructor?
为澄清起见,在这种情况下,Plugin
被视为主要类.
To clarify, in this case, Plugin
is considered the main class.
我了解足够的Java语法来编写中间级别的插件,但是对Java本身了解的不够,不知道这两种方式之间的区别.
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.
例如,我用来创建Map
的Maps
类使用一个静态工厂方法(我希望我正确地使用了该术语),该方法称为使用类而不是对象.
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.
推荐答案
区别在于静态工厂方法更加灵活.它可以通过各种方式返回实例.它可以做其他方面的事情.它可以具有更具描述性的名称.可以通过静态导入或继承以其简单名称(例如foo(args)
)调用它.
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.
这篇关于Java:通过构造函数和静态方法进行初始化之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!