在Java中,如何根据其构造函数选择其函数的Runnable类?
例如:
Class A implements Runnable {
public A(int var) {
//things go here
}
public A(int var1, String var2) {
//things go here
}
public void run() {
//do (a) if Constructor A(int var)
//do (b) if Constructor A(int var1, String var2)
}
}
答案 0 :(得分:3)
你可以这样做:
class A implements Runnable {
int constructor;
public A(int var) {
//things go here
constructor = 1;
}
public A(int var1, String var2) {
//things go here
constructor = 2;
}
public void run() {
if (constructor == 1) ...
if (Constructor == 2) ...
}
}
但我建议使用多态。看起来这是两类不同的对象。
答案 1 :(得分:3)
我会设置一个Strategy模式:
class A implements Runnable {
private final ExecutionStrategy strategy;
public A(int var) {
strategy = new FooStrategy();
}
public A(int var1, String var2) {
strategy = new BarStrategy();
}
public void run() {
strategy.exec();
}
interface ExecutionStrategy {
public void exec();
}
private class FooStrategy implements ExecutionStrategy {
@Override
public void exec() {
//implement me
}
}
private class BarStrategy implements ExecutionStrategy {
@Override
public void exec() {
//implement me
}
}
}