Thursday, May 10, 2012

Design Pattern Study Notes 3 - Template Method




















Problem:
need to define the process or logic on the top class, and implement the detail logic at lower classes

Solution:
Template method pattern

1) top abstract class
=============== Template.java ================

package test.pattern.template;

public abstract class Template {

public void process() {
beforeOperation();
operation();
afterOperation();
}

private void beforeOperation() {
System.out.println("before action.");
}

private void afterOperation() {
System.out.println("after action.");
}

public abstract void operation();
}

2) sub class to implement the abstract method
================= TemplateImpl.java ==============

package test.pattern.template;

public class TemplateImpl extends Template {

public void operation() {
System.out.println("do something.");

}
}

3) the other sub class to implement the abstract method

================== TemplateImpl2.java =================
package test.pattern.template;

public class TemplateImpl2 extends Template {

public void operation() {
System.out.println("do something else.");
}
}


4) test class
=================== Client.java ==================
package test.pattern.template;

public class Client {

public static void main(String[] args) {
Template t1 = new TemplateImpl();
t1.process();

Template t2 = new TemplateImpl2();
t2.process();

}

}

This is the output:

before action.
do something.
after action.
before action.
do something else.
after action.



No comments:

Post a Comment