[英]How can I avoid dependencies between methods?
我有以下方法:
protected ArrayList<String> prepInstaller(RemoteSession session) {
ArrayList<String> installCommand = new ArrayList<String>();
installer.setInstallOption(getCommand());
installer.setInstallProperties(generateInstallProperties());
installer.setTestHome(getTestHome(session));
switch (installer.getInstallOption()) {
case ("addon"):
installer.setAddOnScriptPath(getAddOnScriptPath(session, true));
installer.setAddOnImageLocation(getAddOnPath(session, true));
installCommand.add(installer.getInstallCommand());
break;
case ("install"):
installer.setImageLocation(getImageLocation(session, true));
installCommand.add(installer.getInstallCommand());
break;
case ("patch"):
case ("rollback"):
installer.setPatchLocationPath(getPatchPath(session, true));
for(String currentPatch: installer.getPatches()) {
installCommand.add(installer.getInstallCommand(currentPatch));
}
break;
}
return installCommand;
}
我的问题是这一行:
installCommand.add(installer.getInstallCommand());
包含installer.getInstallCommand()
,除非运行以下命令,否则它将包含空对象:
installer.setInstallOption(getCommand());
installer.setInstallProperties(generateInstallProperties());
installer.setTestHome(getTestHome(session));
其中...该方法依赖于正在运行的先前方法,这是不希望的。 我已将installer
定义为静态工厂:
public static InstallData getInstance() {
if (instance == null) {
instance = new InstallData();
}
return instance;
}
我已经看过使用生成器模式,但是似乎有点不合时宜。 我找不到完整的版本。 我不想使用构造函数,因为它会很杂乱,我将需要几个。
我还尝试构造一个包含所有set
方法的对象,然后将该对象传递到一个返回getInstallCommand()
的新类中,但这也很混乱。
欢迎想法:)
正如问题中指出的那样,在对象处于非法状态时实例化对象或调用方法不是理想的行为。 在大多数情况下,对象创建需要4个或更多参数,但是其中一些参数可以有合理的默认值,可以通过要求必要的参数并替换可选参数来使用伸缩构造函数(反)模式。
在其他情况下,尤其是当参数为相似/相同类型时,将使用构建器模式。 它们不是一次指定所有参数,而是一个一个地设置,最后使用Builder
对象实例化所需的类。
该问题在某些情况下涉及“混乱”代码。 虽然这对于任意代码都是正确的,但设计模式是
在软件设计中给定上下文中对常见问题的通用可重用解决方案。
因此,如果正确实现,它要么适用于用例,要么不适用,但不应该是“混乱”的。 我还建议您看看常用设计模式的 java实现。 也许,可以找到适合问题领域的更合适的替代方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.