Definition -
As the name states, this pattern will provide a template of steps to be followed inorder to complete a task or part of a task.
There will be an interface or an abstract class which will be used by concrete classes and implement or extend all the steps.
Scenario -
Let us take the same example of a car manufacturing plant where in the plant manufactures a car or sedan. The process to build either car is the same hence -
1) We will have an abstract class called buildcar with the following functions - getchassis, addwheel, addengine, addseats.
package TemplatePattern;
public abstract class buildcar {
public abstract void getchassis();
public abstract void addengine();
public abstract void addwheels();
public final void build() {
getchassis();
addengine();
addwheels();
System.out.println("Completed building");
}
}
2) We will have two concrete classes called hatchback and sedan.
hatchback.java
package TemplatePattern;
public class hatchback extends buildcar {
@Override
public void getchassis() {
System.out.println("Getting chassis for a hatchback");
}
@Override
public void addengine() {
System.out.println("Adding engine to hatchback");
}
@Override
public void addwheels() {
System.out.println("Adding wheels to hatchback");
}
}
sedan.java
package TemplatePattern;
public class sedan extends buildcar {
@Override
public void getchassis() {
System.out.println("Getting chassis for a sedan");
}
@Override
public void addengine() {
System.out.println("Adding engine to sedan");
}
@Override
public void addwheels() {
System.out.println("Adding wheels to sedan");
}
}
3) The below code shows the demo for the same
package TemplatePattern;
public class templatedemo {
public static void main(String[] args) {
buildcar bc=new hatchback();
bc.build();
}
}
Place to use -
1) When have a scenario which can be made into templates.
2) You want to control what happens at each step and avoid rewriting the code in multiple places.
The code used above is present in the link
No comments:
Post a Comment