首页 > 其他 > 详细

工厂模式

时间:2018-01-16 22:40:52      阅读:171      评论:0      收藏:0      [点我收藏+]
 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

工厂模式

原文:https://www.cnblogs.com/celine/p/8297647.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!