模板方法模式:
定义:定义一个模板类抽象类,共同特性(非抽象方法)到当前类中实现,其他特性(抽象方法)到对应的子类中实现
模板方法 示例+注释
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 
 | 
 
 
 
 
 public abstract class Template {
 
 
 
 
 
 
 
 public final void templateMethod(){
 
 commonMethod1();
 
 commonMethod2();
 
 specifiedMethod1();
 if(isRun()){
 
 specifiedMethod2();
 }
 }
 
 
 
 
 
 protected boolean isRun() {
 return true;
 }
 
 private void commonMethod1() {
 System.out.println("共同属性一");
 }
 private void commonMethod2() {
 System.out.println("共同属性二");
 }
 
 protected abstract void specifiedMethod1();
 
 protected abstract void specifiedMethod2();
 }
 
 | 
各子类实现:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 
 | class Specified1 extends Template {protected void specifiedMethod1() {
 System.out.println("Specified1   method 1");
 }
 
 protected void specifiedMethod2() {
 System.out.println("Specified1   method 2");
 }
 }
 class Specified2 extends Template {
 protected void specifiedMethod1() {
 System.out.println("Specified2   method1");
 }
 protected void specifiedMethod2() {
 System.out.println("Specified2   method2");
 }
 
 @Override
 protected boolean isRun() {
 return false;
 }
 }
 public class Test{
 
 public static void main(String[] args) {
 Template specified1 = new Specified1();
 Template specified2 = new Specified2();
 specified1.templateMethod();
 System.out.println("........................");
 specified2.templateMethod();
 }
 
 
 }
 
 | 
结果:
| 12
 3
 4
 5
 6
 7
 8
 
 | 共同属性一共同属性二
 Specified1   method 1
 Specified1   method 2
 ........................
 共同属性一
 共同属性二
 Specified2   method1
 
 |