https://sourcemaking.com/design_patterns/template_method/java/2
Template Method design pattern
- Standardize the skeleton of an algorithm in a base class "template" method
- Common implementations of individual steps are defined in the base class
- Steps requiring peculiar implementations are "placeholders" in base class
- Derived classes can override placeholder methods
- Derived classes can override implemented methods
- Derived classes can override and "call back to" base class methods
abstract class Generalization {
public void findSolution() {
stepOne();
stepTwo();
stepThr();
stepFor();
}
protected void stepOne() { System.out.println( "Generalization.stepOne" ); }
abstract protected void stepTwo();
abstract protected void stepThr();
protected void stepFor() { System.out.println( "Generalization.stepFor" ); }
}
abstract class Specialization extends Generalization {
protected void stepThr() {
step3_1();
step3_2();
step3_3();
}
protected void step3_1() { System.out.println( "Specialization.step3_1" ); }
abstract protected void step3_2();
protected void step3_3() { System.out.println( "Specialization.step3_3" ); }
}
class Realization extends Specialization {
protected void stepTwo() { System.out.println( "Realization .stepTwo" ); }
protected void step3_2() { System.out.println( "Realization .step3_2" ); }
protected void stepFor() {
System.out.println( "Realization .stepFor" );
super.stepFor();
} }
class TemplateMethodDemo {
public static void main( String[] args ) {
Generalization algorithm = new Realization();
algorithm.findSolution();
} }
Output
Generalization.stepOne
Realization .stepTwo
Specialization.step3_1
Realization .step3_2
Specialization.step3_3
Realization .stepFor
Generalization.stepFor
댓글 없음:
댓글 쓰기