定义一个方法,安排算法的步骤,算法每一步的详细实现策略可以延迟到子类执行。
可以在算法里定义hook,让客户选择性的改变算法的策略,而不需要本身算法的步骤。
代码示例:
1 package templmethod; 2 3 abstract class Audi { 4 5 protected boolean isWhistle; 6 7 protected void start(){ 8 System.out.println("starting...."); 9 } 10 11 protected void stop(){ 12 System.out.println("stopped...."); 13 } 14 15 protected abstract void driveNormal(); 16 17 protected abstract void driveSlowly(); 18 19 protected void reverse(){ 20 setWhistle(); 21 if(isWhistle){ 22 System.out.println("倒车请注意...倒车请注意..."); 23 System.out.println("backing now...."); 24 }else{ 25 System.out.println("backing now...."); 26 } 27 } 28 29 public void setWhistle(){ 30 this.isWhistle = true; 31 } 32 33 34 }
1 package templmethod; 2 3 public class AudiA4 extends Audi{ 4 5 @Override 6 public void driveNormal() { 7 System.out.println("A4 high-end driving normally...."); 8 } 9 10 @Override 11 public void driveSlowly() { 12 System.out.println("A4 high-end driving slowly...."); 13 } 14 15 @Override 16 public void setWhistle() { 17 isWhistle = false; 18 } 19 20 21 }
1 package templmethod; 2 3 public class AudiC5 extends Audi { 4 5 @Override 6 public void driveNormal() { 7 System.out.println("C5 stdeady driving normally...."); 8 } 9 10 @Override 11 public void driveSlowly() { 12 System.out.println("C5 stdeady driving slowly...."); 13 } 14 15 @Override 16 public void setWhistle() { 17 isWhistle = true; 18 } 19 20 }
1 package templmethod; 2 3 public class Driver { 4 private Audi myCar; 5 6 /*传说中的定义算法的方法,具体的步骤由它规定,任何人都不可以改变; 7 * 但是每一步是可以通过子类的延迟实现,来定义的 8 */ 9 public void driveCar(){ 10 myCar.start(); 11 myCar.driveNormal(); 12 System.out.println("GPS提示:前方90度急转弯...."); 13 myCar.driveSlowly(); 14 System.out.println("GPS提示:前方无路可走...."); 15 myCar.reverse(); 16 } 17 18 public void stopCar(){ 19 myCar.stop(); 20 } 21 22 public void buyCar(Audi audi){ 23 this.myCar = audi; 24 } 25 }
1 package templmethod; 2 3 public class Client { 4 public static void main(String[] args) { 5 Driver driver = new Driver(); 6 driver.buyCar(new AudiA4()); 7 driver.driveCar(); 8 9 System.out.println("--------------------------------------"); 10 11 driver.buyCar(new AudiC5()); 12 driver.driveCar(); 13 14 } 15 }
输出结果:
starting.... A4 high-end driving normally.... GPS提示:前方90度急转弯.... A4 high-end driving slowly.... GPS提示:前方无路可走.... backing now.... -------------------------------------- starting.... C5 stdeady driving normally.... GPS提示:前方90度急转弯.... C5 stdeady driving slowly.... GPS提示:前方无路可走.... 倒车请注意...倒车请注意... backing now....