Vipercold
Vipercold

Reputation: 609

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 !

Upvotes: 0

Views: 418

Answers (2)

StackFlowed
StackFlowed

Reputation: 6816

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.

Upvotes: 2

rgettman
rgettman

Reputation: 178333

You can make ProcessOnFileNetwork a subclass of ProcessOnFile. That way, you can access the logic in the process() method of ProcessOnFile by calling super.process() in the process() method of ProcessOnFileNetwork.

You probably just typed your code in your question, but just in case, interface and implements must be all lowercase.

Upvotes: 1

Related Questions