如何使用“静态工厂方法”而不是建设者? [英] How to use "Static factory methods" instead of constructors?
本文介绍了如何使用“静态工厂方法”而不是建设者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有效的java说
考虑提供静态工厂方法而不是构造函数
Effective java says "Consider providing static factory methods instead of constructors"
如果你有一个
class A {
public static A getInstance() {
return new A();
}
}
为A类提供此方法是否有意义,而不是在代码中调用新的A()。
Does it make sense to provide this method for class A , rather than call new A() in the code.
推荐答案
参见这里可以很好地阐述您可能想要这样做的主要原因。总结:
See here for a nice exposition of the main reasons you might want to do this. In summary:
- 命名为构造函数。
- 如果合适,可以返回null。
- 如果合适,可以返回派生类的实例。
- 在实例化泛型类型的变量时减少详细程度。
- Named "constructors".
- Can return null, if appropriate.
- Can return an instance of a derived class, if appropriate.
- Reduce verbosity when instantiating variables of generic types.
另一个原因是文章没有提到:可以实现有趣的逻辑以避免一直创建新对象(基于参数的缓存,回收等) 。
Another reason comes to mind that the article doesn't mention: Can implement interesting logic to avoid creating new objects all the time (caching based on parameters, recycling, etc.).
这篇关于如何使用“静态工厂方法”而不是建设者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文