1 package com.jdk7.chapter2.factory; 2 3 public class Factory { 4 //定义具体的类型,该类型只属于该类 5 public static final String SELECTTION_SORT = "SelectSort"; 6 public static final String BUBBLE_SORT = "bubbleSort"; 7 public static final String LINEARINSERT_SORT = "linearInsertSort"; 8 public static final String QUICK_SORT = "quickSort"; 9 10 //因为这里调用了静态常量SELECTTION_SORT等,所以该方法要为静态的 11 public static SortNumber getSortNumber(String id){ 12 if(id.equalsIgnoreCase(SELECTTION_SORT)){ 13 return new SelectSort(); 14 }else if(id.equalsIgnoreCase(BUBBLE_SORT)){ 15 return new BubbleSort(); 16 }else if(id.equalsIgnoreCase(LINEARINSERT_SORT)){ 17 return new LinearInsertSort(); 18 }else if(id.equalsIgnoreCase(QUICK_SORT)){ 19 return new QuickSort(); 20 }else{ 21 System.out.println("factory中无该类型"); 22 return null; 23 } 24 } 25 }
1 package com.jdk7.chapter2.factory; 2 3 public class FactoryTest { 4 public static void printIntArray(int[] array){ 5 if(array==null){ 6 return; 7 }else{ 8 for(int i=0;i<array.length;i++){ 9 System.out.print(array[i]+" "); 10 } 11 } 12 System.out.println(); 13 } 14 15 public static void main(String[] args) { 16 int[] array = new int[] {5,8,7,6,1,4,3,2}; 17 18 System.out.println("===============SELECTTION_SORT==============="); 19 int[] a = Factory.getSortNumber(Factory.SELECTTION_SORT).sortASCNumber(array); 20 printIntArray(a); 21 22 System.out.println("===============BUBBLE_SORT==============="); 23 int[] b = Factory.getSortNumber(Factory.BUBBLE_SORT).sortASCNumber(array); 24 printIntArray(b); 25 26 System.out.println("===============LINEARINSERT_SORT==============="); 27 int[] c = Factory.getSortNumber(Factory.LINEARINSERT_SORT).sortASCNumber(array); 28 printIntArray(c); 29 30 System.out.println("===============QUICK_SORT==============="); 31 int[] d = Factory.getSortNumber(Factory.QUICK_SORT).sortASCNumber(array); 32 printIntArray(d); 33 } 34 } 35 36 执行结果: 37 ===============SELECTTION_SORT=============== 38 1 2 3 4 5 6 7 8 39 ===============BUBBLE_SORT=============== 40 1 2 3 4 5 6 7 8 41 ===============LINEARINSERT_SORT=============== 42 1 2 3 4 5 6 7 8 43 ===============QUICK_SORT=============== 44 1 2 3 4 5 6 7 8
其余类代码详见:http://www.cnblogs.com/celine/p/8290254.html