在对象转换方面,以下两种方法的首选方法是什么?
使用 asX() 方法进行对象转换
public class Foo {
int foo;
public Bar asBar() {
return new Bar(foo);
}
}
class Bar {
int bar;
public Bar(int bar) {
this.bar = bar;
}
}
使用构造函数进行对象转换
public class Foo {
int foo;
}
class Bar {
int bar;
public Bar(int bar) {
this.bar = bar;
}
public Bar(Foo foo) {
this.bar = foo.foo;
}
}
与另一种方法相比,我不确定这两种方法的优点(在可维护性、可扩展性等方面)。既定标准是什么?
我接受保罗·博丁顿在评论中指出的问题相当广泛,但希望在这个问题结束之前进行一些有用的讨论。
我看到的很多使用,我个人喜欢的是很多JDK本身使用的样式,它涉及目标类中的静态工厂方法。最终目标是使代码易于阅读。
例如:
Integer.fromString("42")
从OP中的示例借出:
public class Foo {
int foo;
}
class Bar {
int bar;
public static Bar fromFoo(Foo foo) {
return new Bar(foo.foo);
}
public Bar(int bar) {
this.bar = bar;
}
}
这样,有人可以从Foo
创建Bar
,并且这样做时代码读取良好:
Bar bar = Bar.fromFoo(foo);
它读起来几乎像英语,而不是COBOL!