这个问题的解决主要取决于是什么决定了当前的策略是什么。为简单起见,我假设所有策略的 UI 都是相同的。
实际上,您将创建一个构建器类或工厂方法。沿着这条线的东西:
interface StrategyPicker {
public Strategy getStrategy();
}
// Most likely used in the JFrame it is added to
class StrategyPickerUI extends JPanel implements StrategyPicker {
// initialize the panel with all the widgets
// and implement the getStrategy method. the getStrategy
// method should be called after the input is done in this
// panel (such as clicking an Ok or Apply button)
}
// You can also make one for the console app
class StrategyPickerSimple implements StrategyPicker {
// ...
}
如果你想真正花哨,你可以创建一个简单的工厂类来删除创建到它自己的类中的行为:
public class StrategyFactory() {
public static Strategy createStrategyFromParameters(StrategyParams sp) {
// creates the Strategy object... doesn't need to be public static
// and if it isn't, it will help making unit tests easier
}
// This nested class could be split up to StrategyAParams,
// StrategyBParams, StrategyCParams
public class StrategyParams {
data paramA;
int paramB_A;
int paramB_B;
int paramC_A;
String paramC_B;
float paramC_C;
}
}
// in StrategyPickerUI class
public getStrategy() {
StrategyParams sp = new StrategyParams();
sp.paramB_A = myJTextFieldParamB_A.getText();
// and so on...
return StrategyFactory.createStrategyFromParameters(sp);
}
如果您想保持 UI 非单体,则将职责拆分给自己的对象。希望这可以帮助。