JAVA Design Patterns - Template Mode

Template role model

The algorithm defines a skeleton of the operation, some steps to subclasses delay. Template Method lets subclasses may not change the structure of certain steps of an algorithm of the algorithm to redefine.

The main solution: common methods, but in each sub-class re-write this approach.

When to use: There are some common methods.

How to solve: abstracting these generic algorithms.

The key code: the abstract class implements, other steps implemented in a subclass.

 

Sample code:

Exam.java

/ **
* @Classname Exam
* abstract test @Description
* @Created by xiangty
* /
public abstract class AbstractExam {

/ **
* test start
* /
abstract void examBegin ();

/ **
* during the examination
* /
abstract void duringTheExamination ();

/ **
end exam *
* /
abstract void examEnd ();


public void Final exam () {
examBegin ();

duringTheExamination ();

examEnd ();
}

}
ChineaseExam.java
/ **
* @Classname ChineaseExam
* @Description language examinations class
* @Created by xiangty
* /
public class ChineaseExam the extends AbstractExam {

@Override
void examBegin () {
System.out.println ( "language examinations start ...");
}

@Override
void duringTheExamination () {
System.out.println ( "Chinese examination ...");
}

@Override
examEnd void () {
System.out.println ( "end language examinations ...");
}

}
MathExam.java

/ **
* @Classname MathExam
* @Description math test class
* @Created by xiangty
* /
public class MathExam the extends AbstractExam {

@Override
void examBegin () {
System.out.println ( "math test start ...");
}

@Override
void duringTheExamination () {
System.out.println ( "math test ...");
}

@Override
void examEnd () {
System.out.println ( "math test end ...");
}

}
ExamTest .java

/ **
* @Classname ExamTest
* @Description template pattern test class
* @Created by xiangty
* /
public class ExamTest {

public static void main (String [] args) {
AbstractExam chineaseExam new new ChineaseExam = ();
chineaseExam.exam ();

= new new MathExam mathExam MathExam ();
mathExam.exam ();
}

}
advantages: 1, the same part of the package, a variable extension portion. 2, extracts the common code, easy to maintain. 3, the behavior control by the parent class, subclass achieved.

Disadvantages: each requires a different implementation to implement a subclass, resulting in an increase of the number of classes, making the system more bulky.

Be used: 1, a number of methods common subclass, and the same logic. 2, important, complex methods can be considered as a template method.

Note: To prevent malicious operations, general template methods plus final keyword.
--------------------- 

Guess you like

Origin www.cnblogs.com/ly570/p/10954543.html