Reputation: 609
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
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
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