Template method defines the
steps to execute an algorithm and it can provide default implementation that
might be common for all or some of the subclasses.
package oops.design.patterns.template;
public abstract class InterviewProcess {
abstract void written();
abstract void technical();
abstract void manager();
abstract void hrRounds();
// Template method - Sequence of processes.
public final void judgeCandidate()
{
written();
technical();
manager();
hrRounds();
}
}
package oops.design.patterns.template;
public class OrangeInterview extends InterviewProcess
{
@Override
void written()
{
System.out.println("written : Orange!");
}
@Override
void technical()
{
System.out.println("technical : Orange!");
}
@Override
void manager()
{
System.out.println("manager : Orange!");
}
@Override
void hrRounds()
{
System.out.println("hr rounds : Orange!");
}
}
package oops.design.patterns.template;
public class ExpediaInterview extends InterviewProcess
{
@Override
void written()
{
System.out.println("written : Expedia!");
}
@Override
void technical()
{
System.out.println("technical : Expedia!");
}
@Override
void manager()
{
System.out.println("manager : Expedia!");
}
@Override
void hrRounds()
{
System.out.println("hr rounds : Expedia!");
}
}
package oops.design.patterns.template;
public class TestCandidate {
public static void main(String[] args) {
InterviewProcess orangeInterview = new OrangeInterview();
orangeInterview.judgeCandidate();
System.out.println("\n");
InterviewProcess expediaInterview = new ExpediaInterview();
expediaInterview.judgeCandidate();
}
}
Output:
written :
Orange!
technical :
Orange!
manager :
Orange!
hr rounds :
Orange!
written :
Expedia!
technical :
Expedia!
manager :
Expedia!
hr rounds :
Expedia!
Template Method Pattern in JDK
1.All non-abstract methods of
java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.
2.All non-abstract methods of
java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap.
Things to remember
1.Template method should be final.
2.Template method should consist of certain
steps whose order is fixed and for some of the methods; implementation differs
from base class to subclass.
No comments:
Post a Comment