Skip to content

Instantly share code, notes, and snippets.

@slmanju
Created January 26, 2018 09:58
Show Gist options
  • Save slmanju/c04a1be0e3c91e90dfc7386bbddd7f7b to your computer and use it in GitHub Desktop.
Save slmanju/c04a1be0e3c91e90dfc7386bbddd7f7b to your computer and use it in GitHub Desktop.
Template Method design pattern
public abstract class AbstractTemplate {
public final void execute() {
operationInitialize();
operation1();
if (hook()) {
operation2();
}
System.out.println("we are done..");
}
protected abstract void operationInitialize();
protected abstract void operation1();
protected void operation2() {
// do something in sub class as required
}
protected boolean hook() {
return false;
}
}
public class TemplateA extends AbstractTemplate {
@Override
protected void operationInitialize() {
System.out.println("hi i'm A");
}
@Override
protected void operation1() {
System.out.println("doing operation 1 in A");
}
@Override
protected void operation2() {
System.out.println("doing operation 2 in A");
}
@Override
protected boolean hook() {
return true;
}
}
public class TemplateB extends AbstractTemplate {
@Override
protected void operationInitialize() {
System.out.println("hi i'm B");
}
@Override
protected void operation1() {
System.out.println("operation 1 in B");
}
}
public class TemplateMethodDemo {
public static void main(String[] args) {
AbstractTemplate templateA = new TemplateA();
templateA.execute();
System.out.println("\n-----------------------\n");
AbstractTemplate templateB = new TemplateB();
templateB.execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment