我正在创建一个带有抽象方法 example(boolean b, String s)
的抽象类,该方法接受 2 个参数。
我想创建一些在该抽象方法中使用的方法,但我需要它们使用相同的参数。因此,与其经常使用 foo(b,s)
,不如只使用 foo()
。
我想我可以以某种方式将它们存储在类里面。但是,我的方法可能会被发送垃圾邮件,因此它一定不会变慢。
public abstract class Example {
public abstract void example(boolean b, String s);
public void foo() {
// This method needs the parameters from the above method.
}
}
可能的解决方案:
public abstract class Example {
protected boolean b;
protected String s;
public abstract void example();
public void foo() {
// This method can now use 'b' and 's'
}
public void run(boolean b, String s) {
this.b = b;
this.s = s;
example();
}
}
如果我像上面最后一个例子那样使用这些参数,它会使过程变慢吗?
如果一个线程想使用这个方法,而另一个线程还没有完成,会不会有问题?
最佳答案
在处理速度之前,让我们先处理正确性:
Will it cause problems if a thread wants to use this method while another is not finished yet?
假设两个线程共享同一个对象,答案是"is"。
但是,如果您能让每个线程都使用自己的类实例,那么答案就是“否”,因为其他线程的重新分配只能在共享对象上进行。
If I use these parameters like in the last example above, will it make the process any slower?
两种实现之间的任何速度差异都是最小的,属于过早的微优化类别。如果从可读性的角度来看在对象上保存参数是有意义的,并且如果它不会产生并发问题,那么就这样做;否则,继续使用参数。
关于java - 参数与字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34416512/