Template mode (Template Pattern)
An abstract class (template) defines the method of implementation class, subclass specific realization of the template method, called when the abstract class way call.
Objective: skeleton class defines a method, extended to achieve specific subclasses.
The main solution: some of the ways GM, but in each sub-category are overridden this method.
When to use : Some common methods.
How to solve: these general algorithm in the abstract template.
The key code: implemented in an abstract class, other steps implemented in a subclass.
Be used: a plurality of sub-class have a common method, and the same logic; repeat complicated methods.
Advantages: no need to change the portion of the package, the extended portion may be varied; extracting common code, easy to maintain; behavior controlled by the parent, (in particular) receiving class implemented by subclasses.
Cons: each of the different sub-class implementation will need to write a subclass of a template, increase the number of sub-categories, large systems.
Note: to prevent malicious acts, the template method generally add the final keyword.
Create an abstract class (template)
. 1 / ** 2 * @author : wooch . 3 * @Create: 2020/02/14 . 4 * / . 5 public abstract class Game { . 6 abstract void the initialize (); . 7 abstract void startPlay (); . 8 abstract void endPlay (); 9 // template 10 public Final void Play () { . 11 // initialization 12 is the initialize (); 13 is // start 14 startPlay (); 15 // End 16 endPlay (); . 17 } 18 is }
Create a subclass (Cricket)
1 /** 2 * @author: wooch 3 * @create: 2020/02/14 4 */ 5 public class Cricket extends Game { 6 @Override 7 void initialize() { 8 System.out.println("Cricket Game Initialized!"); 9 } 10 11 @Override 12 void startPlay() { 13 System.out.println("Cricket Game Started."); 14 } 15 16 @Override 17 void endPlay() { 18 System.out.println("Cricket Game Finished."); 19 } 20 }
Create a subclass (Football)
1 /** 2 * @author: wooch 3 * @create: 2020/02/14 4 */ 5 public class Football extends Game { 6 @Override 7 void initialize() { 8 System.out.println("Football Game Initialized!"); 9 } 10 11 @Override 12 void startPlay() { 13 System.out.println("Football Game Started."); 14 } 15 16 @Override 17 void endPlay() { 18 System.out.println("Football Game Finished."); 19 } 20 }
Demonstration Results
1 /** 2 * @author: wooch 3 * @create: 2020/02/14 4 */ 5 public class TemplatePatternTest { 6 public static void main(String[] args) { 7 Game game = new Cricket(); 8 game.play(); 9 System.out.println(); 10 game = new Football(); 11 game.play(); 12 } 13 }
operation result
1 Cricket Game Initialized! 2 Cricket Game Started. 3 Cricket Game Finished. 4 5 Football Game Initialized! 6 Football Game Started. 7 Football Game Finished.