Search code examples
javadesign-patternsstrategy-pattern

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


Im implementing a strategy pattern and in a specific situation, one strategy must use another strategy implementation as part of it.

For Example:

interface ProcessStrategy{

    void process();

}

public class ProcessOnFile implements ProcessStrategy{

    void process(){


    }
}

public class ProcessOnFileNetwork implements ProcessStrategy{

    void process(){


    }
}

In this case, processOnFileNetwork will encapsulate the logic inside ProcessOnFile plus some especific logic..

How can i add this functionality without repeat the code??

Thanks !


Solution

  • You could use abstract class concept.

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

    Note abstract classes can have data variables too which can be utilized.