In a word: logic is the same, concrete implementation is different
1. Use the scene
A. Multiple subclasses have common methods, and the logic is essentially the same;
B. Refactoring, the same code is extracted to the parent class
2. Advantages
A. The invariant algorithm is encapsulated into the parent class, the variable part is placed in the subclass, and the extension is convenient;
B. Extraction of public parts for easy maintenance;
C. The concrete logic is implemented by the parent class, and the subclass implements the concrete method;
3. Disadvantages
A. The behavior of subclasses has an effect on the parent class, and the execution result of the subclass affects the result of the parent class;
B. For beginners, it is not easy to read;
4. Specific application
Application is very extensive, such as: servlet,struts,mybatis,spring
5. code example
/**
* Template mode sample, abstract template class
* @author Mid Lee
* @date 2013-12-01 * * Public
abstract class Modeltemplete {
//Basic method is as protected type as possible, accords with Dimitri Law
protected abstract void method1 ();
protected abstract void Method2 ();
Prevent malicious action, generic template method plus final keyword, do not allow overwrite
final public void Templatemethod () {
this.method1 ();
THIS.METHOD2 ();
}
/**
* Specific template Class 1 */Public
class ModelTempleteConcrete1 extends Modeltemplete {
@Override
protected void Method1 () {
System.out.println ("Concrete1 method1 ...");
}
@Override
protected void Method2 () {
System.out.println ("Concrete1 method2 ...");
}
/**
* Specific template Class 2 */Public
class ModelTempleteConcrete2 extends Modeltemplete {
@Override
protected void Method1 () {
System.out.println ("Concrete2 method1 ...");
}
@Override
protected void Method2 () {
System.out.println ("Concrete2 method2 ...");
}
/**
* Template mode Test class
* Run Result:
* Concrete1 method1 ...
* Concrete1 method2
... * Concrete2 method1
... * Concrete2 method2
... * @author Mid Lee
* @date 2013-12-01
/public class Modeltempletetest {public
static void main (Stri Ng[] args) {
modeltemplete a = new ModelTempleteConcrete1 ();
Modeltemplete B = new ModelTempleteConcrete2 ();
Call Template Method
A.templatemethod ();
B.templatemethod ();
}
reference materials:
1. Qin Xiaobo "Zen of Design Patterns" Machinery Industry society 2010.1