如何使用另一个内部战略实施战略模式?

时间:2015-02-26 19:19:09

标签: java design-patterns strategy-pattern

我实施战略模式,在特定情况下,一个战略必须使用另一个战略实施作为其中的一部分。

例如:

interface ProcessStrategy{

    void process();

}

public class ProcessOnFile implements ProcessStrategy{

    void process(){


    }
}

public class ProcessOnFileNetwork implements ProcessStrategy{

    void process(){


    }
}

在这种情况下,processOnFileNetwork将封装ProcessOnFile中的逻辑以及一些特定的逻辑。

如何在不重复代码的情况下添加此功能?

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用抽象类概念。

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
    }
}

注意抽象类也可以包含可以使用的数据变量。

答案 1 :(得分:1)

您可以将ProcessOnFileNetwork设为ProcessOnFile的子类。这样,您可以通过process() ProcessOnFile super.process()方法中的process()调用ProcessOnFileNetwork} interface方法中的逻辑。

您可能只是在问题中输入了代码,但为了以防万一,implements和{{1}}必须全部为小写。