设计模式-模板方法

定义:定义一个操作中算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变算法的结构即可重定义该算法中的某些特定步骤。

UML类图:

 1 public abstract class AbstractTemplate {
 2 
 3     public abstract int[] sort(int[] array);
 4     
 5     public void print(int[] array){
 6         int[]  sortResult = sort(array);
 7         if(sortResult != null){
 8             for(int i = 0; i < sortResult.length; i++)
 9                 System.out.println("sortResult["+i+"] = " + sortResult[i]);
10         }
11     }
12 }
13 public class ConcreteClass extends AbstractTemplate {
14 
15     @Override
16     public int[] sort(int[] array) {
17         // TODO Auto-generated method stub
18         for (int i = 1; i < array.length; i++) {
19             for (int j = i; j > 0; j--) {
20                 if (array[j] < array[j - 1]) {
21                     int temp = array[j - 1];
22                     array[j - 1] = array[j];
23                     array[j] = temp;
24                 } else
25                     break;
26             }
27         }
28         return array;
29     }
30 
31 }
32 public class Main {
33 
34     public static void main(String[] args) {
35         ConcreteClass cc = new ConcreteClass();
36         int[] array = new int[]{5,6,11,2,3,29};
37         cc.print(array);
38     }
39 }

 

posted on 2015-04-09 11:20  jaden.xu  阅读(111)  评论(0)    收藏  举报

导航