是的,这是标准做法。这不是常见(在实例方法中,更常见于static
s),但它是完全标准的。
Foo
中的代码在很大程度上是无关紧要的:如果代码由于某种原因需要Foo
以外的其他实例,则创建实例并使用它是非常正常的。
这不是真的比任何一个创建不同类的两个实例的方法更奇:
class Foo {
void method() {
Bar b1 = new Bar();
Bar b2 = new Bar();
// ...
}
}
据推测,method
需求都Bar
实例。同样,doSomething
显然需要Foo
而不是this
。
你特别看到的一个地方是具有流畅接口的不可变对象,其中大多数方法都会返回对象的一个实例,并改变了某些方面。
public class Thingy {
private int a;
private int b;
public Thingy(a, b) {
this.a = a;
this.b = b;
}
public Thingy withA(int newA) {
return new Thingy(newA, this.b);
}
public Thingy withB(int newB) {
return new Thingy(this.a, newB);
}
public int getA() {
return this.a;
}
public int getB() {
return this.b;
}
// ...
}
通常withX
方法比这更有趣,但你的想法... String
就是这样的一个例子,作为5tingr4y指出:toUpperCase
,substring
,...
恕我直言,这不是,是非常罕见的(除非该方法是静态的)。 –