簡體   English   中英

如何避免方法之間的依賴性?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM