Behavioural Design Patterns: Template method
Previously we used the strategy pattern to in order to solve the problem of choosing various speeding algorithms based on the road type. The next behavioural design pattern we are going to use is the template method.
By using the template method we define the skeleton of the algorithm and the implementation of certain steps is done by subclasses.
Thus we have methods with concrete implementations, and methods without any implementation. Those methods will be implemented based on the application logic needed to be achieved.
Imagine the case of a coffee machine. There are many types of coffees and different ways to implement them, however some steps are common and some steps although they vary they also need to be implemented. Processing the beans, boiling, processing the milk, they are all actions that differ based on the type of coffee. Placing to a cup and service however are actions that do no differentiate.
package com.gkatzioura.design.behavioural.template; public abstract class CoffeeMachineTemplate { protected abstract void processBeans(); protected abstract void processMilk(); protected abstract void boil(); public void pourToCup() { /** * pour to various cups based on the size */ } public void serve() { processBeans(); boil(); processMilk(); pourToCup(); } }
Then we shall add an implementation for the espresso. So here’s our espresso machine.
package com.gkatzioura.design.behavioural.template; public class EspressoMachine extends CoffeeMachineTemplate { @Override protected void processBeans() { /** * Gring the beans */ } @Override protected void processMilk() { /** * Use milk to create leaf art */ } @Override protected void boil() { /** * Mix water and beans */ } }
As you see we can create various coffee machine no matter how different some steps might be. You can find the sourcecode on github.
Published on Java Code Geeks with permission by Emmanouil Gkatziouras, partner at our JCG program. See the original article here: Behavioural Design Patterns: Template method Opinions expressed by Java Code Geeks contributors are their own. |