静态工厂方法vs实例(正常)构造函数? [英] Static factory methods vs Instance (normal) constructors?
本文介绍了静态工厂方法vs实例(正常)构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在两种语言都可用的语言中,您是否希望看到返回实例的实例构造函数或静态方法?
例如,如果从创建
: String
char []
<
String.FromCharacters(chars);
new String(chars);
解决方案>
在有效Java,第2版中,Joshua Bloch一定会推荐前者。有几个原因我可以记住,毫无疑问,我不能:
- 你可以给这个方法一个有意义的名字。如果你有两种方法来构造一个实例,它们都接受一个int,但对int有不同的含义,使用一个正常的方法使调用代码更容易阅读。
- A
- 您可以为潜在预期失败情况返回null,而构造函数总是 可返回值或抛出异常
- 您可以返回一个非声明的类型(例如返回派生类)
- 作为工厂,可能多次返回对同一对象的引用
缺点:
In a language where both are available, would you prefer to see an instance constructor or a static method that returns an instance?
For example, if you're creating a String
from a char[]
:
String.FromCharacters(chars);
new String(chars);
解决方案
In Effective Java, 2nd edition, Joshua Bloch certainly recommends the former. There are a few reasons I can remember, and doubtless some I can't:
- You can give the method a meaningful name. If you've got two ways of constructing an instance both of which take an int, but have different meanings for that int, using a normal method makes the calling code much more readable.
- A corollary of the first - you can have different factory methods with the same parameter list
- You can return null for "potentially expected failure" cases whereas a constructor will always either return a value or throw an exception
- You can return a type other than the declared (e.g. return a derived class)
- You can use it as a factory, to potentially return a reference to the same object several times
The downsides:
- It's not as idiomatic, currently - developers are more used to seeing "new"
- If you see "new" you know you're getting a new instance (modulo the oddity I mentioned recently)
- You need to make appropriate constructors available for subclasses
- In C# 3, constructor calls are able to set fields/properties in a compact manner with object initializer expressions; the feature doesn't apply to static method calls
这篇关于静态工厂方法vs实例(正常)构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文