Created
January 26, 2018 09:58
-
-
Save slmanju/c04a1be0e3c91e90dfc7386bbddd7f7b to your computer and use it in GitHub Desktop.
Template Method design pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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