簡體   English   中英

如何使用內含另一個策略的策略實施策略模式?

[英]How to implement strategy pattern using a strategy that have another one inside?

在實施策略模式的過程中,在特定情況下,一項策略必須使用另一項策略實施作為其一部分。

例如:

interface ProcessStrategy{

    void process();

}

public class ProcessOnFile implements ProcessStrategy{

    void process(){


    }
}

public class ProcessOnFileNetwork implements ProcessStrategy{

    void process(){


    }
}

在這種情況下,processOnFileNetwork將封裝在ProcessOnFile內的邏輯以及一些特定於邏輯的邏輯。

如何在不重復代碼的情況下添加此功能?

謝謝 !

您可以使用抽象類概念。

public abstract class ProcessStrategy{
    public void process(){
        // Common code goes here
    }

}

public class ProcessOnFile extends ProcessStrategy{

    public void process(){
        super();
        // Class specific code goes here
    }
}

public class ProcessOnFileNetwork extends ProcessStrategy{

    public void process(){
        super();
        // Class specific code goes here
    }
}

注意抽象類也可以具有可以使用的數據變量。

您可以ProcessOnFileNetwork的子類ProcessOnFile 這樣,您可以訪問邏輯的process()的方法ProcessOnFile通過調用super.process()process()的方法ProcessOnFileNetwork

您可能只是在問題中鍵入了代碼,但以防萬一, interfaceimplements必須全部小寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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