I've got an abstract class like this
public abstract Stuff
{
public abstract void doStuff();
}
Several classes are extending Stuff, overriding doStuff(). doStuff() in general performs totally different tasks for each implementation but shares a common part.
Whats the best way to implement this?
I don't want to write someting like:
public void doStuff()
{
doTheCommonPart();
...
}
in every extending class.
You could use the Template Method Pattern:
public abstract Stuff
{
public abstract void doStuff();
public void doTheCommonPart() {
// ...
}
// Template method
public final void doIt() {
doTheCommonPart();
doStuff();
}
}
Then, your client classes just have to call the template method doIt(). It will execute the common code part, as well as the concrete implementation of the abstract method doStuff().
Either:
Place the common code in a protected method in the Stuff class and call it from each implementation of doStuff; or
Add the common code to your abstract Stuff class and call another abstract method.
E.g. (1)
public abstract Stuff
{
public abstract void doStuff();
protected void commonCode()
{
//...
}
}
or (2)
public abstract Stuff
{
public void doStuff()
{
// Do the common stuff initially...
// ...
// Then call the subclass implementation
doRealStuff();
}
public abstract void doRealStuff();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With