1. Concept: DefineAlgorithmAnd delay some implementation steps to the subclass.
Move the unchanged behavior to the superclass to remove duplicates in the subclass.CodeTo reflect his advantages.
2. UML diagram:
3. Code:
Public abstract class templete {private void beforeoperation () {system. Out. println ("this Acton before the operation! ");} Private void afteroperation () {system. Out. println (" this Acton after the operation! ");} // It must be postponed to the subclass (Implementation class) to execute protected abstract void operation (); Public void topoperation () {beforeoperation (); Operation (); afteroperation () ;}} public class templeteimpl extends templete {protected void operation () {system. out. println ("the operation action is executed in the method of servicea instance! ") ;}} Public class templettest {public static void main (string [] ARGs) {templete = new templeteimpl (); templete. topoperation ();}}
4. Application scenarios:
1) Implement the unchanged part of an algorithm at one time and leave the variable behavior to the subclass for implementation.
2) common behaviors in each subclass should be extracted and centralized into a common parent class to avoid code duplication. First, identify the differences in the existing code and separate the differences into new operations. Finally, replace these different codes with a template method that calls these new operations.